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

时间:2016-11-09 14:48:01

标签: php arrays

我想将3个具有唯一键的小数组合并为1个大数组,但是当我修改大数组中的值时,我希望它也反映在相应的小数组中。

例如,我有这3个小数组:

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

我希望有$bigArray将每个密钥的地址链接/映射到小数组的每个值。所以,如果我做了类似的事情:

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

然后它会将$arr2['key4']修改为相同的值('something else')。

如果我尝试这样的话:

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

使用映射值的键创建一个多维数组会产生不幸的影响。

2 个答案:

答案 0 :(得分:2)

我发现的两种方式

<?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);

具有功能的第三种方式

$big = [];
$bindToBig = function (&$a) use (&$big) {
    foreach (array_keys($a) as $k) {
        $big[$k] = &$a[$k];
    }
};

$bindToBig($arr1);
$bindToBig($arr2);
$bindToBig($arr3);

答案 1 :(得分:1)

您无法以这种方式绑定数据,但您可以将它们链接到同一个对象中:

class ArrayLink {
    public $bigArray;
    public $linkedChildrenArray;
    protected $childrenArray;

    public function __construct( $childrenArray ) {
        $this->childrenArray = $childrenArray;
    }

    public function changeValueForKey( $arrKey, $arrValue ) {
        foreach ( $this->childrenArray as $key => $value ) {
            foreach ( $value as $subKey => $subValue ) {
                if ( $arrKey == $subKey ) {
                    $this->bigArray[ $subKey ]              = $arrValue;
                    $this->childrenArray[ $key ][ $subKey ] = $arrValue;
                }
            }
        }
        $this->linkedChildrenArray = (object) $this->childrenArray;
    }
}

如您所见,$ arr2现在需要从$arrayLink对象访问:

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

$arrayLink = new ArrayLink( array( 'arr1' => $arr1, 'arr2' => $arr2, 'arr3' => $arr3 ) );
$arrayLink->changeValueForKey( 'key3', 'new value for key 3' );

echo $arrayLink->bigArray['key3']; //new value for key 3
echo $arrayLink->linkedChildrenArray->arr2['key3']; //new value for key 3