我有以下代码:
$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');
$d = array($a, $b, $c);
Run Code Online (Sandbox Code Playgroud)
打印$d
输出:
Array
(
[0] => Array
(
[a] => some value
[b] => some value
[c] => some value
)
[1] => Array
(
[a] => another value
[d] => another value
[e] => another value
[f] => another value
)
[2] => Array
(
[b] => some more value
[x] => some more value
[y] => some more value
[z] => some more value
)
)
Run Code Online (Sandbox Code Playgroud)
我将如何组合数组键并最终得到以下输出?
Array
(
[0] => Array
(
[a] => some value
[b] => some value
[c] => some value
[d] =>
[e] =>
[f] =>
[x] =>
[y] =>
[z] =>
)
[1] => Array
(
[a] => another value
[b] =>
[c] =>
[d] => another value
[e] => another value
[f] => another value
[x] =>
[y] =>
[z] =>
)
[2] => Array
(
[a] =>
[b] => some more value
[c] =>
[d] =>
[e] =>
[f] =>
[x] => some more value
[y] => some more value
[z] => some more value
)
)
Run Code Online (Sandbox Code Playgroud)
提前感谢您提供有关如何实现这一目标的任何帮助.
是的,你可以array_merge
在这种情况下使用:
$a = array('a' => 'some value', 'b' => 'some value', 'c' => 'some value');
$b = array('a' => 'another value', 'd' => 'another value', 'e' => 'another value', 'f' => 'another value');
$c = array('b' => 'some more value', 'x' => 'some more value', 'y' => 'some more value', 'z' => 'some more value');
$d = array($a, $b, $c);
$keys = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($d)) as $key => $val) $keys[$key] = '';
$data = array();
foreach($d as $values) {
$data[] = array_merge($keys, $values);
}
echo '<pre>';
print_r($data);
Run Code Online (Sandbox Code Playgroud)
编辑:另一种方法是创建密钥对值与键配对为空,然后,映射每个$d
并合并:
$keys = array_keys(call_user_func_array('array_merge', $d));
$key_pair = array_combine($keys, array_fill(0, count($keys), null));
$values = array_map(function($e) use ($key_pair) {
return array_merge($key_pair, $e);
}, $d);
Run Code Online (Sandbox Code Playgroud)