将当前元素与PHP多维数组中的前一元素进行比较

时间:2018-05-09 14:16:16

标签: php arrays

目标是将当前数组元素qty与之前的数组进行比较,如果符合条件则返回成功,即:if current element qty is 0 and the previous element qty is greater than 5 return

研究不断出现PHP的current(), next(),prev()工具,但是我没有得到这些尝试的希望:

1.
for($i = 0; $i < $length -1; ++$i){
  if(current($myArray[0]['qty']) == 0 && prev($myArray[0]['qty']) > 5){
    echo 'success!';
  }
}

2.
foreach($myArray as $item){
  if(current($item['qty']) == 0 && prev($item['qty'] > 5)){
    echo 'success!';
  } else {
    continue;
  }
}

不可否认,我不熟悉所有PHP的可用工具和选项,所以如果还有其他我应该学习和使用的东西我会感激建议。< / p>

这是我的示例数组:

$myArray = Array
(
  [0] => Array
    (
      [0] => foo
      [name] => foo
      [1] => 15
      [qty] => 15
    )
  [1] => Array
    (
      [0] => bar
      [name] => bar
      [1] => 0
      [qty] => 0
    )
  [2] => Array
    (
      [0] => baz
      [name] => baz
      [1] => 47
      [qty] => 47
    )
)

我想要的结果如下是自动发送电子邮件:**bar** is empty, check **foo** for replenishment!

1 个答案:

答案 0 :(得分:2)

prev()循环期间,不能使用for来获取数组的前一个元素,因为循环不会更改内部数组指针。此外,prev()函数应该在数组上使用,而不是在值上使用。

您可以使用foreach()的索引并检查$array[$index-1]是否存在以及其值是否与您的条件匹配:

$myArray = array(
  0 => array(0 => 'foo', 'name' => 'foo', 1 => 15, 'qty' => 15),
  1 => array(0 => 'bar', 'name' => 'bar', 1 => 0, 'qty' => 0),
  2 => array(0 => 'baz', 'name' => 'baz', 1 => 47, 'qty' => 47)
);

foreach ($myArray as $index => $item) {
  // if index is greater than zero, you could access to previous element:
  if ($item['qty'] == 0 && $index > 0 && $myArray[$index-1]['qty'] > 5) {
    $current_name = $item['name'];
    $previous_name = $myArray[$index-1]['name'];
    echo "'$current_name' is empty, check '$previous_name' for replenishment!";
  } else {
    continue;
  }
}

输出:

  

&#39;杆&#39;是空的,检查&#39; foo&#39;补货!