Build dynamic array in PHP Build dynamic array in PHP php php

Build dynamic array in PHP


Your question is confusing. This is what I understand:

You have the following:

  • $t, which is an object.
  • $t->user, also an object.
  • $t->user[0]->name = 'wilson'
  • $t->user[0]->first = 'carl'

You say you need to get:

  • $t->name = 'wilson'
  • $t->first = 'carl'

You say 'phil' in the question, but the given object $t has no reference to a 'phil' so I don't know if 'phil' appears out of thin air, or what.

Is this a correct view of the problem? If so, you need to clarify this in the question. saying $t > user > 0 (object) name makes no sense.

Sorry this is an "answer", I just couldn't fit all of this in a comment. I will delete it if you clarify the question. Hopefully I am not the only person confused by this.


$t = object()$t > user = object()$t > user > 0 (object) name = 'wilson';$t > user > 0 (object) first = 'carl';

This is not valid PHP code. If you want $t in the format you show, just do this:

$t = array( 'name' => 'wilson', 'first name' => 'phil');

Now $t is an array, with keys 'name' and 'first name'.

Your foreach loop doesn't make any sense. $t is an array of two strings. Looping over it will just give the values 'wilson' and 'phil'.

EDIT: Assuming $t was given to you, then your for loop should look like this:

foreach($t as $a) {       foreach($a as $l) {          $arr[$l->{0}->name] = $l->{0}->first;      }  }

You can't do $l->0. You need to wrap the 0 in {}. $l->{0}.