[英]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.