加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP在数组之间添加缺少的键

发布时间:2020-12-13 13:31:22 所属栏目:PHP教程 来源:网络整理
导读:我有以下代码: $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 val
我有以下代码:
$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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读