douzhang7603 2010-12-09 21:33
浏览 112
已采纳

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

I have a list in php with the following structure:

$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. What's the best way to accomplish this?

  • 写回答

2条回答 默认 最新

  • doukougua7873 2010-12-09 21:38
    关注
    $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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现