在for循环中,如何使用php检查每个先前值的当前值
我的数组:
在数组列表[prolabelpos] =>0
中有3次,仅在for循环中如何执行[prolabelpos] =>0
1次。如何使用所有先前的值检查当前数组,以及如何[prolabelpos] =>0
在for循环中执行一次
Array (
[0] => Array ( [productlabel_id] => 6 [prolabelpos] => 0 )
[1] => Array ( [productlabel_id] => 5 [prolabelpos] => 6 )
[2] => Array ( [productlabel_id] => 4 [prolabelpos] => 0 )
[3] => Array ( [productlabel_id] => 3 [prolabelpos] => 5 )
[4] => Array ( [productlabel_id] => 2 [prolabelpos] => 0 )
)
我的代码:
<?php
$prev = null;
foreach ($result as $key => $value) {
$label_position = $value['prolabelpos'];
if ($prev != $label_position) {
echo "my code";
}
$prev = $label_position;
}
答案 0 :(得分:2)
您可以在foreach
或array_map
$arr =
Array (
'0' => Array ( 'productlabel_id' => 6, 'prolabelpos' => 0 ),
'1' => Array ( 'productlabel_id' => 5, 'prolabelpos' => 6 ),
'2' => Array ( 'productlabel_id' => 4, 'prolabelpos' => 0 ),
'3' => Array ( 'productlabel_id' => 3, 'prolabelpos' => 5 ),
'4' => Array ( 'productlabel_id' => 2 ,'prolabelpos' => 0 )
);
$traversed = array();
foreach($arr as $value){
if(in_array($value['prolabelpos'], $traversed)){
//This has been traversed before
}else{
/* Apply your Logic */
$traversed[] = $value['prolabelpos'];
}
}
使用array_map
$arr = Array (
'0' => Array ( 'productlabel_id' => 6, 'prolabelpos' => 0 ),
'1' => Array ( 'productlabel_id' => 5, 'prolabelpos' => 6 ),
'2' => Array ( 'productlabel_id' => 4, 'prolabelpos' => 0 ),
'3' => Array ( 'productlabel_id' => 3, 'prolabelpos' => 5 ),
'4' => Array ( 'productlabel_id' => 2 ,'prolabelpos' => 0 )
);
$traversed = array();
array_map(function($v) use (&$traversed){
if(in_array($v['prolabelpos'], $traversed)){
//This has been traversed before
}else{
/* Apply your Logic */
$traversed[] = $v['prolabelpos'];
}
}, $arr);