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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度