1

When I execute the code below: Code:

<?php

$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'][] = $jim;
$data['abc'][] = $bob;

print_r($data);
?>

I receive the following output:

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

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

What I am expecting is the following output:

   Array
(
    [abc] => Array
        (
            [Jim] => 1
            [Bob] => 1
        )

)

How can I achieve this? To rephrase the question, how can I keep it to a single sub-array per a supplied key?

2
  • Jim and Bob are arrays by your own declaration, you have to change them first Commented Aug 30, 2013 at 13:37
  • @ØHankyPankyØ mayor bee. But Glavic supplied a solution. Commented Aug 30, 2013 at 13:39

3 Answers 3

5
$data = array();
$jim = array('Jim'=>1);
$bob = array('Bob'=>1);
$data['abc'] = array_merge($jim, $bob);

print_r($data);
Sign up to request clarification or add additional context in comments.

5 Comments

Still this will produce 3 levels
@Darhazer That's what the OP required
His title kinda contradicts his question. He can just remove the [] if he wants to keep it at two levels.
I have updated my original question because Darhazer provided the output I was expecting.
You have to understand the problem, not the question, otherwise you fall in the trap of the XY problem ;)
1

You are creating array ($data['abc']) which contains an array ([]) of arrays($jim, $bob) It's the same as writing:

$data['abc'][0] = array('jim' => 1);
$data['abc'][1] = array('bob' => 1);

What you want is probably:

$data['abc'] = array();
$data['abc'] = array_merge($data['abc'], $jim, $bob);

1 Comment

Ah yes, this is the output I am expecting. I will change my original question to mirror. Side note you have mege it should be merge
0

Jim and Bob are array indexes by your own declaration, you have to change them first

<?php

$data = array();
$data['abc']["Jim"] =1;
$data['abc']["Bob"] = 2;

print_r($data);
?>

Demo

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.