【问题标题】:Laravel 4 - Convert arrays of objects into individual objectsLaravel 4 - 将对象数组转换为单个对象
【发布时间】:2013-10-20 10:05:24
【问题描述】:

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

我的意思是,我在下面列出了这些数据:

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

【问题讨论】:

    标签: php arrays object laravel laravel-4


    【解决方案1】:

    这是你的意思吗?

    $book0 =& $books[0];
    $book1 =& $books[1];
    $book2 =& $books[2];
    
    echo $book0->id
    

    【讨论】:

      【解决方案2】:

      您的意思不是 100% 清楚,您是希望这三个对象作为单独的变量,还是只需要一种访问它们的方法。

      一个简单的 foreach 就足够了。

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

      另外,Eugen 提供的答案会获取变量的特定索引供您使用。

      【讨论】:

        【解决方案3】:

        你可以使用

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

        DEMO.

        因此,如果您的 $arrayOfObjects 内部包含三个对象,那么每个对象都将从数组中提取并存储在 list 提供的变量中,您可以使用第一个对象,例如

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

        另外,使用循环你可以这样做

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

        【讨论】:

          猜你喜欢
          • 2019-02-12
          • 2019-09-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-11-28
          • 2016-10-10
          • 2022-01-15
          相关资源
          最近更新 更多