Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 542
natalia Avatar asked Dec 30 '11 21:12

natalia


1 Answers

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.

like image 164
Logan Serman Avatar answered Oct 21 '22 08:10

Logan Serman