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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?