doubaoxue5788 2013-11-12 23:03
浏览 28
已采纳

合并并重新排列嵌套的键/值

I have an array like this:

array(
  0 => array(
    'name' => 'colors',
    'options' => array(
      array('name'=>'red', 'price'=>'2'),
      array('name'=>'blue', 'price'=>'3')
    )
  ),
  1 => array(
    'name' => 'sizes',
    'options' => array(
      array('name'=>'small', 'price'=>'5'),
      array('name'=>'large', 'price'=>'10')
    )
  ),
);

I want to merge all of the nested options arrays' name/prices into one, so it'll be like this:

array(
  'red' => '2',
  'blue' => '3',
  'small' => '5',
  'large' => '10'
);

I have a feeling this is very simple, but anything I try seems too convoluted. Any help would be appreciated.

...and yes, I just posted almost the same question not too long ago. This is a bit different, and what I meant to ask in the first place - oops, sorry.

  • 写回答

4条回答 默认 最新

  • dongxia19772008 2013-11-12 23:11
    关注

    I'm not sure if this can be done with internal methods such as array_merge(), array_combine(), etc since your structure seems quite special. But how about iterating over the array and building a new one yourself?

    function customRearrange($arr) {
        $result = array();
        foreach ($arr as $group) {
            foreach ($group['options'] as $option) {
                // prevents values from being overwritten, uncomment if unwanted
                if (!array_key_exists($option['name'], $result))
                    $result[ $option['name'] ] = $option['price'];
            }
        }
        return $result;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?