gpt4 book ai didi

laravel - 在Laravel中将数组转换为集合

转载 作者:行者123 更新时间:2023-12-03 13:24:57 25 4
gpt4 key购买 nike

我在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"
}
]

“分类不起作用”是指未对项目进行分类。

最佳答案

编辑;我知道这个问题会根据标题获得很大的成功,因此针对这些人的TLDR将使用collect()帮助程序创建一个Collection实例。在回答提问者的简介时:
如果你有

$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方法返回由该集合表示的基础数组。

关于laravel - 在Laravel中将数组转换为集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49083535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com