2 dim arrays combined to 3 dim's

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cloudbase
Forum Newbie
Posts: 15
Joined: Tue Dec 13, 2011 12:11 pm

2 dim arrays combined to 3 dim's

Post 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')
);
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: 2 dim arrays combined to 3 dim's

Post 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.
cloudbase
Forum Newbie
Posts: 15
Joined: Tue Dec 13, 2011 12:11 pm

Re: 2 dim arrays combined to 3 dim's

Post 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)
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: 2 dim arrays combined to 3 dim's

Post 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;
Post Reply