简体   繁体   English

获取PHP多维数组的下一个和上一个元素

[英]get next and previous elements of PHP multi-dimensional array

I have a list in php with the following structure: 我在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
);

what I'd like to do is get the array before and after the array where order == $center. 我想做的是在order == $ center的数组之前和之后获取数组。 What's the best way to accomplish this? 做到这一点的最佳方法是什么?

$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];

If $center matches the first or last element of the array, though, before or after won't be valid -- what do you want to consider the "before" and "after" elements? 但是,如果$ center与数组的第一个或最后一个元素匹配,则之前或之后将是无效的-您想考虑“ before”和“ after”元素吗? Should the array be treated as a circular structure? 应该将数组视为圆形结构吗?

I would say 我会说

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM