Page 1 of 1

Combine arrays into multidimensional arrays.

Posted: Sat Mar 14, 2009 11:32 am
by socket1
So I have three arrays:

Code: Select all

 
Names Array
(
    [0] => Bob
    [1] => Joe
    [2] => Foo
)
 
Age Array
(
    [0] => 20
    [1] => 30
    [2] => 15
)
 
Another Array
(
    [0] => 105
    [1] => 87
    [2] => 35
)
 
I want to combine them into an array that looks like this:

Code: Select all

 
Combined Array
(
    [Bob] => array (
                          [Age] => 20
                          [Another] => 105
                         )
    [Joe] => array (
                          [Age] => 30
                          [Another] => 87
                         )
    [Foo] => array (
                          [Age] => 15
                          [Another] => 35
                         )
)
 
Is there a specific function to do this and use the first array (names) as the index?

Re: Combine arrays into multidimensional arrays.

Posted: Sun Mar 15, 2009 9:19 am
by socket1
I figured it out, here's the code if it helps anybody:

Code: Select all

 
<?php
$Names = array('Bob',
               'Joe',
               'Foo');
 
$Ages = array('20',
              '30',
              '15');
 
$Foo = array('Foo1',
             'Foo2',
             'Foo3');
 
$Combined = array();
 
foreach ($Names as $num => $name) {
    $Combined[''.$name.''] = array('age' => ''.$Ages[$num].'',
                                   'foo' => ''.$Foo[$num].'');
}
 
print_r($Combined);
?>
 
I really overestimated the difficulty of this.

Re: Combine arrays into multidimensional arrays.

Posted: Mon Mar 16, 2009 10:26 am
by pickle
You don't need to concatenate your values with empty strings.

This works fine:

Code: Select all

$Combined[$name] = ...