dongyun7571 2017-06-27 11:59
浏览 29
已采纳

如何将多维数组键更改为Childs键值?

I'm trying to rename the parent keys in a Multidimensional Array to the value of a child key.

For example in the code below I would like to change the key [0] to [111] and the key [1] to [222] so it is easy for me to identify keys later for an array merge.

Array (
[0] => Array ( [product_id] => 111 [product_name] => Foo [quantity] => 4 )
[1] => Array ( [product_id] => 222 [product_name] => Bar [quantity] => 2 )
)

I've tried various ways of doing this but after entering a loop, I can't work out how to affect the parent key and assume it's impossible after passing it to a variable. Is there an easy solution to change the key I am missing or is it a case of entering the loop and rebuilding a new array with the desired key?

  • 写回答

3条回答 默认 最新

  • duanmu8911 2017-06-27 12:18
    关注

    One-line solution using array_combine and array_column functions:

    $result = array_combine(array_column($arr, 'product_id'), $arr);
    print_r($result);
    

    The output:

    Array
    (
        [111] => Array
            (
                [product_id] => 111
                [product_name] => Foo
                [quantity] => 4
            )
    
        [222] => Array
            (
                [product_id] => 222
                [product_name] => Bar
                [quantity] => 2
            )
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘