对多维数组进行排序,但在 PHP 中保留索引



>我正在对这个数组进行排序

$array =
( 
[Scorebord] => Hyperscore [Ontmoeting_ID] => 1540 [ThuisPloeg_ID] => 1257 [UitPloeg_ID] => 1246 [Wedstrijden] => Array (
[0] => Array (
[Wedstrijd_ID] => 15401 [Speler_Thuis_ID] => 12669 [Speler_Thuis_TSP] => 17) 
[1] => Array (
[Wedstrijd_ID] => 15402 [Speler_Thuis_ID] => 12713 [Speler_Thuis_TSP] => 21) 
[2] => Array (
[Wedstrijd_ID] => 15403 [Speler_Thuis_ID] => 12656 [Speler_Thuis_TSP] => 23) 
[3] => Array (
[Wedstrijd_ID] => 15404 [Speler_Thuis_ID] => 12912 [Speler_Thuis_TSP] => 19)
)
)

通过以下代码以"Speler_Thuis_TSP"作为标准:

usort($json_sorted['Wedstrijden'], function($a,$b){
$c = $a['Speler_Thuis_TSP'] - $b['Speler_Thuis_TSP'];
return $c;
});

这给了我这个数组:

( 
[Scorebord] => Hyperscore [Ontmoeting_ID] => 1540 [ThuisPloeg_ID] => 1257 [UitPloeg_ID] => 1246 [Wedstrijden] => Array (
[0] => Array (
[Wedstrijd_ID] => 15401 [Speler_Thuis_ID] => 12669 [Speler_Thuis_TSP] => 17) 
[1] => Array (
[Wedstrijd_ID] => 15404 [Speler_Thuis_ID] => 12912 [Speler_Thuis_TSP] => 19)
[2] => Array ( 
[Wedstrijd_ID] => 15402 [Speler_Thuis_ID] => 12713 [Speler_Thuis_TSP] => 21) 
[3] => Array (
[Wedstrijd_ID] => 15403 [Speler_Thuis_ID] => 12656 [Speler_Thuis_TSP] => 23) 
)
)

问题是"Wedstrijd_ID"应该保持原来的顺序,即首先是15401,然后是15402、15403和15404。任何想法如何解决这个问题?提前非常感谢...

在此解决方案中,您可以使用array_column获取原始订单,然后通过简单地将新的有序值替换为array_column值来简单地覆盖新订单值。

$original_id_order = array_column($json_sorted['Wedstrijden'], 'Wedstrijd_ID');
usort($json_sorted['Wedstrijden'], function($a,$b){
$c = $a['Speler_Thuis_TSP'] - $b['Speler_Thuis_TSP'];
return $c;
});
foreach($json_sorted['Wedstrijden'] as $key => $value){
$json_sorted['Wedstrijden'][$key]['Wedstrijd_ID'] = $original_id_order[$key];
}

相关内容

最新更新