我有如下数组
array (A => 1)
array (A => 1, B=>2)
array (A => 1, B=>2, C=>3)
array (A => 1, D=>4)
array (A => 1, E=>5)
array (A => 1, F=>6)
array (A => 1, F=>6, G=>8)
array (A => 1, F=>6, H=>9)
array (X => 11)
array (X => 11, Y=22)
array (X => 11, Z=33)
我需要按如下方式构建数组
array(A=>array(B=>2, C=>3, D=>4, E=>5, F=>array(G=>8,H=>9))
X=>array(Y=>22, Z=>33)
答案 0 :(得分:0)
我认为这就是你要找的东西:
$result = array();
foreach ($arrays as $array) {
$ref = &$result;
foreach ($array as $key => $val) {
if (!isset($ref[$key])) {
$ref[$key] = $val;
} elseif (!is_array($ref[$key])) {
$ref[$key] = array();
}
$ref = &$ref[$key];
}
}
这里的键被解释为使用引用遍历数组的路径段。如果还没有值,则存储该值;如果已有值,则将其替换为数组。
但这会产生一些不同的结果:
array (
'A' =>
array (
'B' =>
array (
'C' => 3,
),
'D' => 4,
'E' => 5,
'F' =>
array (
'G' => 8,
'H' => 9,
),
),
'X' =>
array (
'Y' => 22,
'Z' => 33,
),
)