我有以下代码:
$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);
打印$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 ) )
我将如何组合数组键并最终得到以下输出?
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 ) )
提前感谢您提供有关如何实现这一目标的任何帮助.
是的,在这种情况下你可以使用array_merge:
$a = array('a' => 'some value','z' => 'some more value'); $d = array($a,$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);
编辑:另一种方法是使用与空配对的键创建密钥对值,然后映射每个$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);