在Laravel中将数组转换为集合

问题描述 投票:8回答:1

我在PHP中有以下数组:

[
  {
     "website": "example",
     "url": "example.com"
  },
  {
     "website": "example",
     "url": "example.com"
  }
]

现在我想把它转换成一个集合,所以我按键websiteurl排序。但是当我这样做时:

$myArray = collect(websites);

我得到了这个:

 {
      "0": {
         "website": "example",
         "url": "example.com"
      },
      "1": {
         "website": "example",
         "url": "example.com"
      }
    }

并且排序不起作用,我想知道我做错了什么以及如何修复它所以我有一个我可以轻松排序的对象的数组集合。

编辑:我希望输出与此相同:

[
  {
     "website": "example",
     "url": "example.com"
  },
  {
     "website": "example",
     "url": "example.com"
  }
]

通过“排序不起作用”我的意思是项目没有排序。

laravel laravel-5 collections
1个回答
14
投票

如果你有

$collection = collect([
    (object) [
        'website' => 'twitter',
        'url' => 'twitter.com'
    ],
    (object) [
        'website' => 'google',
        'url' => 'google.com'
    ]
]);

然后,将您的数组包装在Collection类的实例中。这意味着它的行为不像典型的数组( - 它将像数组一样,但不要像对待它一样 - )直到你在它上面调用all()toArray()。要删除任何添加的索引,您需要使用values()

$sorted = $collection->sortBy('website');

$sorted->values()->all();

预期产量:

[
     {#769
       +"website": "google",
       +"url": "google.com",
     },
     {#762
       +"website": "twitter",
       +"url": "twitter.com",
     },
]

请参阅文档https://laravel.com/docs/5.1/collections#available-methods

toArray方法将集合转换为普通的PHP数组。如果集合的值是Eloquent模型,则模型也将转换为数组。

all方法返回集合表示的底层数组。

© www.soinside.com 2019 - 2024. All rights reserved.