TotalNewbie
TotalNewbie

Reputation: 1024

Passing an Associative array into another associative array in PHP

apologies if this is a simple fix - I'm having trouble passing a few arrays in PHP. I have two arrays setup eg:

$person = array(
            'height' => 100,
            'build'  => "average",
            'waist'  => 38,
            );

$hobbies = array(
            'climbing' => true,
            'skiing'   => false,
            'waist'    => 38,
            );

now if I perform a print_r() on these arrays they return results as expected.I then insert the 2 arrays into a new array as seen below:

$total = array($person, $hobbies);

using print_r once again returns a new array containing both arrays but it is not associative. However if I try to do the following:

$total = array(
                'person'   <= $person,
                'hobbies'  <= $hobbies,
               );

and I perform a print_r on $total using the code above I am not seeing both arrays with associations. ^ the above data is just an example data but identical in structure in my real app, I get returned the following result:

Array ( [0] => 1 [1] => 1 )

Once again apologies if I am being extremely thick - which I have a feeling I am.

Upvotes: 0

Views: 104

Answers (3)

jszobody
jszobody

Reputation: 28911

It sounds like you want the $total array to have person and hobbies keys for the sub-arrays. If so, simply do this:

$total = array("person" => $person, "hobbies" => $hobbies);

Example with output: http://3v4l.org/5U5Hh

Upvotes: 2

mcryan
mcryan

Reputation: 1576

Your array assignments are the wrong way round: 'person' <= $person should be 'person' => $person.

// Wrong
$total = array(
  'person' <= $person,
  'hobbies' <= $hobbies,
);

// Right
$total = array(
  'person' => $person,
  'hobbies' => $hobbies,
);

Upvotes: 1

Vincent
Vincent

Reputation: 555

You need to use array_merge, if you want to merge both array into a new array.

$result = array_merge($person, $hobbies);

Upvotes: 0

Related Questions