[英]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
. 目标是将当前数组元素
qty
与先前的数组元素进行比较,如果满足条件,则返回成功,即: 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: 研究不断涌现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;
}
}
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. 诚然,我对PHP的所有可用工具和选项都不熟悉,因此,如果我需要学习和使用其他东西,我将不胜感激。
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!
对于自动电子邮件,我希望得到的结果如下:
**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. 您不能在
for
循环中使用prev()
来获取数组的前一个元素,因为该循环不会更改内部数组指针。 Also, the prev()
function should be used on the array, not on a value. 另外,
prev()
函数应在数组上使用,而不是在值上使用。
You can use the index of the foreach()
and check if the $array[$index-1]
exists and if its value match to your condition: 您可以使用
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;
}
}
Output: 输出:
'bar' is empty, check 'foo' for replenishment!
“ bar”为空,请检查“ foo”是否补货!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.