有人可以帮忙解决如何对集合中的键进行排序吗?
我尝试使用sort()
功能,但它不起作用。
当前实施: 公共函数myFunction($ param) { $ collectionOne = collect();
foreach ($param as $keyOne=> $valueOne) {
$collectionTwo = collect();
foreach ($valueOne as $id) {
$result= $this->model()::find($id);
if (!isset($result) || empty($result)) throw new NoRecordFoundException('Not Found');
$resultId = $result->some_id;
if ($collectionTwo->has($resultId)) {
$collectionTwo[$resultId]->push($id);
} else {
$collectionThree= collect($id);
$collectionTwo->put($resultId, $collectionThree);
}
}
$collectionOne->put($keyOne, $collectionTwo->sort());
var_dump($collectionTwo->toArray());
}
return $collectionOne;
}
实际输出:
MyRepository.php:124:
array (size=2)
1 =>
array (size=2)
0 => int 1
1 => int 4
2 =>
array (size=1)
0 => int 2
MyRepository.php:124:
array (size=2)
2 => <--- Not sorted
array (size=1)
0 => int 2
1 => <--- Not sorted
array (size=1)
0 => int 4
预期输出:
MyRepository.php:124:
array (size=2)
1 =>
array (size=2)
0 => int 1
1 => int 4
2 =>
array (size=1)
0 => int 2
MyRepository.php:124:
array (size=2)
1 => <--- Sorted
array (size=1)
0 => int 4
2 => <--- Sorted
array (size=1)
0 => int 2
答案 0 :(得分:0)
试试这个:
$thisCollection = $thisCollection->toArray();
$thisCollection = ksort($thisCollection);
$thisCollection = collect($thisCollection);
我们的想法是将您的集合转换为数组,然后将其转换为ksort,然后使用collect()帮助程序将数组返回到集合。