[英]Comparing current element with previous element in PHP multi-dimensional array
目标是将当前数组元素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的所有可用工具和选项都不熟悉,因此,如果我需要学习和使用其他东西,我将不胜感激。
这是我的示例数组:
$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!
您不能在for
循环中使用prev()
来获取数组的前一个元素,因为该循环不会更改内部数组指针。 另外, 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;
}
}
输出:
“ bar”为空,请检查“ foo”是否补货!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.