排序集合数组
Sorting collection array
任何人都可以帮助如何对集合中的键进行排序吗?
我尝试使用 sort()
函数,但它不起作用。
当前实施:
public 函数 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
试试这个:
$thisCollection = $thisCollection->toArray();
$thisCollection = ksort($thisCollection);
$thisCollection = collect($thisCollection);
想法是将您的集合转换为数组,然后对它进行排序,然后 return 使用 collect() 帮助程序将数组返回到集合。
任何人都可以帮助如何对集合中的键进行排序吗?
我尝试使用 sort()
函数,但它不起作用。
当前实施: public 函数 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
试试这个:
$thisCollection = $thisCollection->toArray();
$thisCollection = ksort($thisCollection);
$thisCollection = collect($thisCollection);
想法是将您的集合转换为数组,然后对它进行排序,然后 return 使用 collect() 帮助程序将数组返回到集合。