在for循环中,如何使用php中的所有先前数组检查当前数组值

时间:2019-05-03 06:04:53

标签: php arrays

在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;
}

1 个答案:

答案 0 :(得分:2)

您可以在foreacharray_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);