开发者

get next and previous elements of PHP multi-dimensional array

I have a list in php with the following structure:

$center = '2';

$all = array(
   array(
     'foo'=&g开发者_运维百科t;'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. 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? 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜