gpt4 book ai didi

php - Yii 中的 CMap::mergeArray

转载 作者:行者123 更新时间:2023-12-02 06:41:38 25 4
gpt4 key购买 nike

我知道 Yii 中的 CMap::mergeArray 合并两个数组。但是我有三个数组,我想让它们通过 CMap::mergeArray 合并。那么如何在 Yii 框架中合并所有三个数组。

最佳答案

这取决于你想要什么。需要注意的主要区别是 CMap 将覆盖现有键,这与内置的 php 函数不同:

If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive)

如果你像上面那样执行 CMap::mergeWith,你只会得到一个由 3 个数组作为子元素组成的新数组:

例如,给定以下结构:

$foo = array (
'a' => 1,
'b' => 2,
'c' => 3,
'z' => 'does not exist in other arrays',
);

$bar = array (
'a' => 'one',
'b' => 'two',
'c' => 'three',
);

$arr = array (
'a' => 'uno',
'b' => 'dos',
'c' => 'tres',
);

使用 CMap::mergeWith 如下:

$map = new CMap();
$map->mergeWith (array($foo, $bar, $arr));
print_r($map);

结果如下:

CMap Object
(
[_d:CMap:private] => Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
[z] => does not exist in other arrays
)

[1] => Array
(
[a] => one
[b] => two
[c] => three
)

[2] => Array
(
[a] => uno
[b] => dos
[c] => tres
)

)

[_r:CMap:private] =>
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)

如果覆盖元素是首选行为,那么以下将起作用:

$map = new CMap ($foo);
$map->mergeWith ($bar);
$map->mergeWith ($arr);
print_r($map);

结果是:

CMap Object
(
[_d:CMap:private] => Array
(
[a] => uno
[b] => dos
[c] => tres
[z] => does not exist in other arrays
)

[_r:CMap:private] =>
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)

但是,如果您想要附加数据,则:

$map = new CMap (array_merge_recursive ($foo, $bar, $arr));
print_r($map);

会带你到那里:

CMap Object
(
[_d:CMap:private] => Array
(
[a] => Array
(
[0] => 1
[1] => one
[2] => uno
)

[b] => Array
(
[0] => 2
[1] => two
[2] => dos
)

[c] => Array
(
[0] => 3
[1] => three
[2] => tres
)

[z] => does not exist in other arrays
)

[_r:CMap:private] =>
[_e:CComponent:private] =>
[_m:CComponent:private] =>
)

关于php - Yii 中的 CMap::mergeArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com