Page 1 of 1

2 dim arrays combined to 3 dim's

Posted: Tue Oct 16, 2012 2:18 pm
by cloudbase
Hello All, I'm here again at my wits end hopping someone can help.

Code: Select all

$array1=array( 'a'=>'4');
$array2=array( 'a'=>'6', 'd'=>'9');
$array3=array( 'b'=>'2', 'c'=>'8', 'd'=>'12');
I've got these arrays above one at a time. I need to change em to below. Where do I start?

Code: Select all

$result=array( 
   'a'=> array( 0=>'4', 1=>'6' ),
   'b'=> array( 0=>'2'),
   'c'=> array( 0=>'8'),
   'd'=> array( 0=>'9', 1=>'12')
);

Re: 2 dim arrays combined to 3 dim's

Posted: Tue Oct 16, 2012 2:39 pm
by requinix
Start with an empty $result and loop through all the key/value pairs in all the arrays: if the key doesn't exist in the $result then add it as =>array(value), and if it does then add the value to the array that's already there.

Or array_merge_recursive() the lot, then go through the result and turn any key=>string you find into key=>array(string) - which arise if the key is unique to one array.

Re: 2 dim arrays combined to 3 dim's

Posted: Tue Oct 16, 2012 3:45 pm
by cloudbase
Thanks requinix , sounds simple enough.
I've been working on some code that hasn't worked. Am I just making it too difficult?

Code: Select all

$array1=array( 'a'=>'4');
$array2=array( 'a'=>'6', 'd'=>'9');
$array3=array( 'b'=>'2', 'c'=>'8', 'd'=>'12');

$array  = array_sum_values( $array1, $array2);
var_dump($array);

function array_sum_values() {
    $return = array();
    $intArgs = func_num_args();
    $arrArgs = func_get_args();
    
    foreach($arrArgs as $arrItem) {
        foreach($arrItem as $k => $v) {
            $return[$k] = array(0=>$v);
        }
    }
    return $return;
}
var_dump- - - - - - - - - - - - - - -
array
'a' =>
array
0 => string '6' (length=1)
'd' =>
array
0 => string '9' (length=1)

Re: 2 dim arrays combined to 3 dim's

Posted: Tue Oct 16, 2012 4:41 pm
by requinix
You skipped over the part where you do two different things depending on whether the key exists in the final array already. If it doesn't then you set the array like you have now, but if it does then you simply append the value into what's there.

Code: Select all

$return[$k][] = $v;