duanfen7676 2014-10-16 17:22
浏览 47

是否存在将关联数组转换为数字数组的最小方法,每个项目都存储键和值?

I simply need to convert, in PHP:

[
    'id' => '1',
    'code' => 'DRX',
    'company_name' => 'Dave Ricks Ltd'
], 
[
    'id' => '2',
    'code' => 'LRT',
    'company_name' => 'LiveRave Ltd'
]

To...

[
    [
        [
            'name' => 'id',
            'value' => '1',
        ],
        [
            'name' => 'code',
            'value' => 'DRX',
        ],
        [
            'name' => 'company_name',
            'value' => 'Dave Ricks Ltd',
        ]
    ], 
    [
        [
            'name' => 'id',
            'value' => '2',
        ],
        [
            'name' => 'code',
            'value' => 'LRT',
        ],
        [
            'name' => 'company_name',
            'value' => 'LiveRave Ltd',
        ]
    ]
]

I know I can do this with a couple of foreach loops but wondered if using some of PHPs array functions I could do the same with less lines of code?

  • 写回答

2条回答 默认 最新

  • dongwei9365 2014-10-16 17:40
    关注

    I'm assuming your initial array is actually

    [
      [
        'id' => '1', 'code' => 'DRX', 'company_name' => 'Dave Ricks Ltd'
      ],
      [
        'id' => '2', 'code' => 'LRT', 'company_name' => 'LiveRave Ltd'
      ]
    ]
    

    since that's the kind of thing you'd get from a database. If I'm wrong and you've posted the actual var_dump/print_r of the array, that's very strange, but we can add a step to reorganize it.

    So all we need to do is

    $input = [
        [
            'id' => '1',
            'code' => 'DRX',
            'company_name' => 'Dave Ricks Ltd',
        ], 
        [
            'id' => '2',
            'code' => 'LRT',
            'company_name' => 'LiveRave Ltd',
        ]
    ];
    
    $output = array_map(function($elem) { 
    
        return [
            ['name' => 'id', 'value' => $elem['id'] ],
            ['name' => 'code', 'value' => $elem['code'] ],
            ['name' => 'company_name', 'value' => $elem['company_name'] ],
        ];
    
    }, $input);
    print_r($output);
    

    If you want the conversion more generic:

    $output = array_map(function($elem) { 
    
        $result = [];
        foreach ($elem as $key => $value) {
            $result[] = ['name' => $key, 'value' => $value];
        }
        return $result;
    
    }, $input);
    print_r($output);
    

    I'm thinking about whether there's an way to remove that inner foreach - but I don't think there is one that's worth the effort.

    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么