如何组合两个不同的多维数组(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"
        ]
    ]
];

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

This should work.

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

$new_structure = array();
foreach($structure as $key =>$value)
{
  if(!is_array($value))
    {
      $new_structure[$value]= $value;
    }else{
      foreach($value as $k =>$v)
        {
          if(!is_array($v))
           { 
              $new_structure[$key][$v]=$v; 
           }else
           {
             foreach($v as $kk => $vv)
             {
                   $new_structure[$k][$vv]=$vv;                                   
             }            
           }
        }
     }
}
print_r($new_structure);exit;

Use $array=array_merge($structure,$data); for more information follow this link how to join two multidimensional arrays in php

You can try by a recursive way. Write a recursive method which takes an array as first argument to alter and the data set as its second argument. This method itself call when any array element is another array, else it alters the key and value with the help of data set.

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

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


function alterKey(&$arr, $data) {
    foreach ($arr as $key => $val) {
        if (!is_array($val)) {
            $data_key = array_search(strtoupper($val), $data);
            $arr[$val] = $data[$data_key];
            unset($arr[$key]);
        } else {
            $arr[$key] = alterKey($val, $data);
        }
    }

    ksort($arr);
    return $arr;
}

alterKey($structure, $data);

echo '<pre>', print_r($structure);

Working demo.