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

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

我正在对该数组进行排序

$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。有什么办法解决该问题吗?提前非常感谢...

php arrays sorting multidimensional-array
1个回答
0
投票

通过此解决方案,您可以使用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];
}
© www.soinside.com 2019 - 2024. All rights reserved.