【问题标题】:In for loop how to check current array value with all previous array in php在for循环中如何使用php中的所有先前数组检查当前数组值
【发布时间】:2019-05-03 06:04:52
【问题描述】:

在for循环中如何使用php检查当前值和每个先前的值

我的数组:

数组列表[prolabelpos] =>0有3次,如何在for循环中只执行一次[prolabelpos] =>0。如何使用所有先前的值检查当前数组和[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;
}

【问题讨论】:

  • 我不太清楚你想要达到什么目的。你只想要prolabelpos = 0 的一个结果?其他情况(ID 为 4 和 2)你想做什么?
  • [prolabelpos] 的前一个值 =>0(其中 id 4 和 2)不需要执行,我只需要执行 [prolabelpos] 的高阶 id 6 值 =>0
  • 好的。然后你需要展示你是如何创建这个数组的。
  • 好吧,我会发布代码
  • 我在上面发布了我的代码

标签: php arrays


【解决方案1】:

您可以通过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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 2013-04-11
    • 2017-09-15
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多