Laravel 4-将对象数组转换为单个对象 [英] Laravel 4 - Convert arrays of objects into individual objects

查看:208
本文介绍了Laravel 4-将对象数组转换为单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望您能将这个简单的问题帮助我,将对象数组转换为单个对象.所以我可以直接调用它们的属性.

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

如何将3个项目数组转换为3个单独的对象?因此,我可以直接调用它们,例如:$books->id,而不是$books[0]->id吗?

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 ?

推荐答案

无论是将三个对象作为单独的变量还是只需要一种访问它们的方法,都不清楚100%的含义.

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.

一个简单的foreach就足够了.

A simple foreach should suffice.

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

或者,Eugen提供的答案将获取变量的特定索引供您使用.

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

这篇关于Laravel 4-将对象数组转换为单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆