Laravel 4 - Convert arrays of objects into individual objects

本小妞迷上赌 提交于 2019-12-25 01:00:49

问题


I hope you can help me with this simple problem in converting arrays of objects to individual objects. So I can directly call their attributes.

What I mean is, I have this data listed below:

array(3) {
  [0]=>
  object(stdClass)#259 (8) {
    ["id"]=>
    int(2)
    ["author_id"]=>
    int(2)
    ["title"]=>
    string(17) "The Emperorasdasd"
    ["publisher"]=>
    string(15) "De publishing"
    ["created_at"]=>
    string(19) "2013-10-11 12:49:00"
    ["updated_at"]=>
    string(19) "2013-10-12 09:44:58"
    ["date_published"]=>
    string(10) "02-12-2013"
    ["name"]=>
    string(8) "John Doe"
  }
  [1]=>
  object(stdClass)#260 (8) {
    ["id"]=>
    int(1)
    ["author_id"]=>
    int(1)
    ["title"]=>
    string(4) "Demo"
    ["publisher"]=>
    string(10) "ooqwwoeqoe"
    ["created_at"]=>
    string(19) "2013-10-12 09:45:31"
    ["updated_at"]=>
    string(19) "2013-10-12 09:45:36"
    ["date_published"]=>
    string(10) "26-12-1993"
    ["name"]=>
    string(11) "Demo"
  }
  [2]=>
  object(stdClass)#261 (8) {
    ["id"]=>
    int(1)
    ["author_id"]=>
    int(1)
    ["title"]=>
    string(12) "Read My Mind"
    ["publisher"]=>
    string(13) "TF Publishing"
    ["created_at"]=>
    string(19) "2013-10-12 09:46:53"
    ["updated_at"]=>
    string(19) "2013-10-12 09:46:53"
    ["date_published"]=>
    string(10) "30-11-2009"
    ["name"]=>
    string(11) "James Mones"
  }
}

How will I convert the 3 item array into 3 individual objects? So I can call them directly like: $books->id, not $books[0]->id ?


回答1:


Its not 100% clear what you mean, whether you want the three objects as seperate variables or you just need a way of accessing them.

A simple foreach should suffice.

foreach ( $collection as $model ) 
{
    $id = $model->id;
}

alternatively the answer supplied by Eugen would grab specific indexes to variables for you to use.




回答2:


Is this, what you mean?

$book0 =& $books[0];
$book1 =& $books[1];
$book2 =& $books[2];

echo $book0->id



回答3:


You can use

list($books1, $books2, $books3) = $arrayOfObjects;

DEMO.

So, if your $arrayOfObjects has three objects inside it then every objects will be extracted from the array and will be stored in variables supplied in the list and you can use the first object like

echo $books1->id;
echo $books2->id;
echo $books3->id;

Also, using a loop you can do it like

foreach($arrayOfObjects as $books) {
    echo $books->id;
}


来源:https://stackoverflow.com/questions/19333160/laravel-4-convert-arrays-of-objects-into-individual-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!