简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM