我知道Yii中的CMap :: mergeArray合并了两个数组.但我有三个数组,我想通过CMap :: mergeArray使它们合并.那么如何在Yii框架中合并所有三个数组.
小智 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',
);
Run Code Online (Sandbox Code Playgroud)
使用CMap :: mergeWith如下:
$map = new CMap();
$map->mergeWith (array($foo, $bar, $arr));
print_r($map);
Run Code Online (Sandbox Code Playgroud)
结果如下:
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] =>
)
Run Code Online (Sandbox Code Playgroud)
如果覆盖元素是首选行为,则以下内容将起作用:
$map = new CMap ($foo);
$map->mergeWith ($bar);
$map->mergeWith ($arr);
print_r($map);
Run Code Online (Sandbox Code Playgroud)
结果如下:
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] =>
)
Run Code Online (Sandbox Code Playgroud)
但是,如果您想要附加数据,那么:
$map = new CMap (array_merge_recursive ($foo, $bar, $arr));
print_r($map);
Run Code Online (Sandbox Code Playgroud)
会让你到那里:
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] =>
)
Run Code Online (Sandbox Code Playgroud)