![](/img/trans.png)
[英]Comparing current element with previous element in PHP multi-dimensional array
[英]get next and previous elements of PHP multi-dimensional array
我在php中具有以下結構的列表:
$center = '2';
$all = array(
array(
'foo'=>'abc',
'bar'=>'def',
'order' => 2
),
array(
'foo'=>'abc',
'bar'=>'def',
'order' => 5
),
array(
'foo'=>'abc',
'bar'=>'def',
'order' => 11
),
//..etc
);
我想做的是在order == $ center的數組之前和之后獲取數組。 做到這一點的最佳方法是什么?
$idx = 0;
foreach ($array as $key => $value) {
if ($value['order'] == $center) {
$idx = $key;
break;
}
}
$before = $all[$idx - 1];
$current = $all[$idx];
$after = $all[$idx + 1];
但是,如果$ center與數組的第一個或最后一個元素匹配,則之前或之后將是無效的-您想考慮“ before”和“ after”元素嗎? 應該將數組視為圓形結構嗎?
我會說
counter = 0;
foreach($all as $order){
if($order['order'] == $center){
break;
}
counter += 1;
}
$prev = $all[$counter -1];
$current = $all[$counter ];
$next = $all[$counter +1];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.