natalia
natalia

Reputation: 839

Build dynamic array in PHP

I need to create an array using a object using different format/structure

I have:

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

I need to get:

$t = array(
 name = wilson
 first name = phil

Here's what I tried and where I'm stuck

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

Now I get an error:

PHP Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in homework1-a-1.php on line 10

What can I do to fix it?

Upvotes: 14

Views: 319

Answers (2)

Logan Serman
Logan Serman

Reputation: 29880

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.

Upvotes: 18

gen_Eric
gen_Eric

Reputation: 227270

$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}.

Upvotes: 0

Related Questions