![](/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.