Combine arrays into multidimensional arrays.

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
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Combine arrays into multidimensional arrays.

Post 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?
socket1
Forum Commoner
Posts: 82
Joined: Mon Dec 08, 2008 7:40 pm
Location: Shokan, New York

Re: Combine arrays into multidimensional arrays.

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Combine arrays into multidimensional arrays.

Post by pickle »

You don't need to concatenate your values with empty strings.

This works fine:

Code: Select all

$Combined[$name] = ...
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply