0

Sorry for the bad title, it's really hard to describe,

$x['is']['tall'] = 'yes';
$y['personal']['age'] = 30;

I have dynamic array keys, and I want to it append to another array key, the result is like

$main['profile']['is']['tall'] = 'yes';                                                                                                                                                                         
$main['profile']['personal']['age'] = 30;

cause when I use json_encode I want to the structure like {"profile":{"is":{"tall":"yes"},"personal":{"age":30}}}

I don't know how to extend the array key like that.

2 Answers 2

2

If you have:

$x['is']['tall'] = 'yes';
$y['personal']['age'] = 30;

Then you can just merge $x and $y to $main like:

$main['profile'] = array_merge($x, $y);

var_dump($main);

echo json_encode($main);

Output:

array(1) {
  ["profile"]=>
  array(2) {
    ["is"]=>
    array(1) {
      ["tall"]=>
      string(3) "yes"
    }
    ["personal"]=>
    array(1) {
      ["age"]=>
      int(30)
    }
  }
}
{"profile":{"is":{"tall":"yes"},"personal":{"age":30}}}

https://3v4l.org/3CREt

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

1 Comment

Yeah. I think I need more coffee. This is how it should be done.
0

try to use array _merge orarray_push.

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.