I am trying to do something like instead of using array_merge_recusive in php
<?php
$A = array("EUR"=>10);
$B = array("EUR"=>10,"JPY"=>20);
$C = $A;
foreach ($B as $key => $value) {
if (!isset($C[$key])) {
$C[$key][] = array();
}
$C[$key] = $value;
}
var_dump($C);
array(2) {
["EUR"]=>
int(10)
["JPY"]=>
int(20)
}
I need to get like this:
array(2) {
["EUR"]=>array(10,10),
["JPY"]=> int(20)
}
EDIT
Check code I am trying here http://codepad.org/x4MuY开发者_开发技巧CiH What I did wrong ,I could not get the expected result?
thanks
For the solution see this paste: http://codepad.org/60IKweVu. I also show the code at the bottom of this answer. This solution is based on the example data in your previous question about this array merge and total if it the same keys.
Note that
array(2) {
["EUR"]=>array(10,10),
["JPY"]=> int(20)
}
is equivalent to
array(2) {
["EUR"]=> array([0] => 10, [1] => 10),
["JPY"]=> int(20)
}
but that the first notation simply does not show the keys of the nested array.
CODE:
<?php
$A = array("EUR"=>10,"USD"=>20);
$B = array("EUR"=>10,"JPY"=>20);
$C = array_merge_recursive($A, $B);
var_dump($C);
//
// This emulates the array_merge_recursive call
//
$C = array();
$allArrays = array($A, $B);
foreach($allArrays as $array) {
foreach ($array as $key => $value) {
if (! isset($C[$key])) {
$C[$key] = array();
}
$C[$key][] = $value;
}
}
foreach ($C as $index => $values) {
if (count($values) == 1) {
$C[$index] = $values[0];
}
}
var_dump($C);
This is the right code:
foreach ($B as $key => $value) {
if (! isset($C[$key]) )
$C[$key] = $value;
else
{
if (isset($C[$key]) && !is_array($C[$key]) )
$C[$key] = array($C[$key]);
$C[$key][] = $value;
}
}
You are creating an empty second level array with
$C[$key][] = array();
which then you overwrite with a single value in
$C[$key] = $value;
Hope this is hint enough...
精彩评论