I know CMap::mergeArray in Yii merges two array. But I have three array and I want to make them merge through CMap::mergeArray. So how to merge all the three array in Yii framework.
It depends on what you want. The key difference to note is that CMap will overwrite existing keys, which is different from the built in php functions:
If each array has an element with the same string key value, the latter will overwrite the former (different from array_merge_recursive)
If you do CMap::mergeWith as above, you'll just be getting a new array consisting of the 3 arrays as subelements:
For example, given the following structure:
$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',
);
Using CMap::mergeWith as follows:
$map = new CMap();
$map->mergeWith (array($foo, $bar, $arr));
print_r($map);
Results in the following:
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] =>
)
If overwriting elements is the preferred behavior, then the following will work:
$map = new CMap ($foo);
$map->mergeWith ($bar);
$map->mergeWith ($arr);
print_r($map);
Which results in:
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] =>
)
If, however, you want the data appended, then:
$map = new CMap (array_merge_recursive ($foo, $bar, $arr));
print_r($map);
Will get you there:
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] =>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With