0

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.

2
  • Are you trying to merge the two arrays into a single array? I'm confused. Commented Jan 8, 2014 at 22:30
  • no I want to try and achieve the following structure Array ( [person] (person_data) [hobbies] => (hobby data) ), in reality I am creating a quiz app and need both the question and answer options within one array but separate - so I can loop around the answer options and do cool stuff. Commented Jan 8, 2014 at 22:32

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, that's what he meant!
thanks - sorry me being really slow putting the assignment operators the wrong way around - its been a long day ;)
will do - theres a time you have to wait before you can accept - I will do ASAP though :)
1

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,
);

1 Comment

^^ thankyou, I knew it would be something stupid I just couldn't spot it sorry guys, thanks for the help.
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.