我知道Yii中的CMap :: mergeArray合并了两个数组。但我有三个数组,我想通过CMap :: mergeArray使它们合并。那么如何在Yii框架中合并所有三个数组。
答案 0 :(得分:8)
这取决于你想要什么。要注意的关键区别是CMap将覆盖现有的密钥,这与内置的php函数不同:
如果每个数组都有一个具有相同字符串键值的元素,那么 后者将覆盖前者(不同于 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] =>
)
答案 1 :(得分:1)
使用array_merge
($ar1, $ar2, $ar3)
或array_merge_recursive
($ar1, $ar2, $ar3)
你也可以使用:
CMap::mergeWith(array($ar1, $ar2, $ar3));
但我不确定前者的结果