简体   繁体   中英

Comparing current element with previous element in PHP multi-dimensional array

The goal is to compare the current array element qty with the previous and if the condition is met return success, ie: if current element qty is 0 and the previous element qty is greater than 5 return .

Research keeps popping up PHP's current(), next(), and prev() tools however I'm not getting the return I hope for with these attempts:

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

Admittedly I'm not familiar with all of PHP's available tools and options so if there's something else I should be learning about and using I'd be grateful for suggestions.

Here's my sample array:

$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
    )
)

My desired result would be the following for an automatic email: **bar** is empty, check **foo** for replenishment!

You cannot use prev() to get the previous element of an array during a for loop, because the loop doesn't change the internal array pointer. Also, the prev() function should be used on the array, not on a value.

You can use the index of the foreach() and check if the $array[$index-1] exists and if its value match to your condition:

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

Output:

'bar' is empty, check 'foo' for replenishment!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM