我想将数组的特定元素放在foreach循环的最后一个循环中。
我确实尝试了以下代码,但我希望有一种更有效的方式来操纵数组。
$sbk = ['LT','MT','KT','GT'];
$sbl = ['LT','MT','GT'];
$numItems = count($sbk);
$i = 0;
foreach($sbk as $rm){
if(in_array($rm, $sbl)){
echo $rm."\n";
}
if(!in_array($rm, $sbl)){
$extra = $rm;
}
if( ++$i === $numItems) {
echo $extra."\n";
}
}
这是我的预期输出:
LT
MT
GT
KT
我希望解决方案处于if else条件下。
foreach($sbk as $rm):
if(in_array($rm, $sbl)){
//print LT MT GT
} else {
//make this the end of the foreach loop.
//since the item is not in the in_array, it should be here at the last loop.
}
endforeach;
答案 0 :(得分:1)
<?php
$sbk = ['LT','MT','KT','GT'];
$sbl = ['LT','MT','GT'];
//Get the differece of sbk and sbl array. you will get the output KT in array.
$result=array_diff($sbk,$sbl);
//Merge the array result and sbl
$final_array = array_merge($sbl,$result);
//fatch the array value
foreach($final_array as $final_arrays){
echo $final_arrays .'<br/>';
}
?>
答案 1 :(得分:0)
您可以使用:
$new_array = array_unique(array_merge($sbk,$sbl));