douxuelv7755 2019-07-24 11:53
浏览 71
已采纳

如何组合两个不同的多维数组(PHP)

I want to combine two different multi-dimensional arrays, with one providing the correct structure (keys) and the other one the data to fill it (values).

Notice that I can't control how the arrays are formed, the structure might vary in different situations.

$structure = [
    "a",
    "b" => [
        "b1",
        "b2" => [
            "b21",
            "b22"
        ]
    ]
];

$data = [A, B1, B21, B22];

Expected result:

$array = [
    "a" => "A",
    "b" => [
        "b1" => "B1",
        "b2" => [
            "b21" => "B21",
            "b22" => "B22"
        ]
    ]
];
  • 写回答

4条回答

  • dongshuohuan5291 2019-07-24 12:39
    关注

    You can use the following code, however it will only work if number of elements in $data is same or more than $structure.

    $filled = 0;
    array_walk_recursive ($structure, function (&$val)  use (&$filled, $data) {
        $val = array( $val => $data[ $filled ] ); 
        $filled++; 
    });
    
    print_r( $structure );
    

    Here is a working demo

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

报告相同问题?

悬赏问题

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