dongshijiao2363 2016-11-09 14:48
浏览 31
已采纳

PHP:将多个数组键的地址链接到另一个更大的数组中

I want to combine 3 small arrays that have unique keys between them into 1 big array but when I modify a value in the big array I want it also to reflect in the corresponding small array.

For example I have these 3 small arrays:

$arr1 = ['key1' => 'data1', 'key2' => 'data2'];
$arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
$arr3 = ['key6' => 'data6'];

I want to have a $bigArray that has each key's address linked/mapped to each value of the small arrays. So if I do something like:

$bigArray['key4'] = 'something else';

then it would modify $arr2['key4'] to the same value ('something else').

If I try something like:

$bigArray = [&$arr1, &$arr2, &$arr3];

It has the unfortunate effect of making a multidimensional array with the keys to the values mapped.

  • 写回答

2条回答 默认 最新

  • douzhuangxuan3268 2016-11-09 15:07
    关注

    Two ways i found

    <?php
    error_reporting(E_ALL);
    
    $arr1 = ['key1' => 'data1', 'key2' => 'data2'];
    $arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
    $arr3 = ['key6' => 'data6'];
    
    $big = [];
    if (true) {
        foreach (['arr1', 'arr2', 'arr3'] as $v) {
            foreach (array_keys($$v) as $k) {
                $big[$k] = &${$v}[$k];
            }
        }
    }
    else {
        foreach ([&$arr1, &$arr2, &$arr3] as &$v) {
            foreach (array_keys($v) as $k) {
                $big[$k] = &$v[$k];
            }
        }
    }
    
    
    $big['key1'] = 'data1mod';
    print_r($big);
    print_r($arr1);
    

    3rd way with function

    $big = [];
    $bindToBig = function (&$a) use (&$big) {
        foreach (array_keys($a) as $k) {
            $big[$k] = &$a[$k];
        }
    };
    
    $bindToBig($arr1);
    $bindToBig($arr2);
    $bindToBig($arr3);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里