【问题标题】:Sorting multidimensional array but keeping index in PHP对多维数组进行排序但在 PHP 中保留索引
【发布时间】:2020-01-26 22:46:11
【问题描述】:

我正在排序这个数组

$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。任何想法如何解决这个问题?非常感谢提前...

【问题讨论】:

  • 当您在['Speler_Thuis_TSP'] 上对您的数组进行排序时,您的['Wedstrijd_ID'] 将改变顺序...如果您想回到['Wedstrijd_ID] 上的排序数组,您可以使用您的原始数组。

标签: php arrays sorting multidimensional-array


【解决方案1】:

从这个解决方案中,您可以使用 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];
}

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 2015-11-02
    • 2015-08-27
    • 2017-10-14
    • 1970-01-01
    • 2017-07-12
    • 2017-04-28
    • 1970-01-01
    相关资源
    最近更新 更多