【问题标题】:I can't get this array to sort properly. Tried many things我无法让这个数组正确排序。尝试了很多东西
【发布时间】:2014-02-21 07:26:31
【问题描述】:

我已经尝试过,并且尝试过,但我只是不知道如何对数组进行排序。我已经按照无数教程尝试对其进行排序,但我认为它不起作用(至少不是我想要的方式)。

我正在尝试制作一个高分表,按分数 ($totalMoney) 从高到低列出玩家 ($players)。

foreach ( $myposts as $post ) : setup_postdata( $post ); 

    $player  = get_the_author_meta('display_name');
    $cash    = get_the_author_meta('cashOnHand');
    $bank    = get_the_author_meta('bankAccount');

    $totalMoney = $cash + $bank;

    $highScores = array($player => $totalMoney);

    asort($highScores);

    foreach($highScores as $key => $value)

        print_r($highScores);


endforeach;

结果总是一个数组,似乎是按“玩家”字段而不是“分数”字段排序的。但无论我做什么,我都无法让它按数组的“分数”字段排序。

 print_r():
Array ( [player3] => 2500 ) Array ( [player2] => 6485 ) Array ( [sd] => 3515 )

您可以看到该数组没有按分数排序(我认为它是按玩家姓名排序的)。

如何让它按播放器键的值排序?

PS:我尝试了所有各种类型:asort、arsort、ksort、krsort,但结果总是相同(参见上面的 print_r()。

【问题讨论】:

  • 那是 PHP 吗?如果是,您应该这样说并标记它。可能会影响答案。
  • 我注意到的一件事是 $highScores 根据您的代码似乎只有一个元素。 $highScores = array($player => $totalMoney); 看起来您每次都在对一个数组进行排序。

标签: php arrays sorting


【解决方案1】:

我认为您在循环的每次迭代中重置高分数组时在代码中犯了一个错误。

请参阅以下内容:

$highScores = array(); // initialize the array

foreach ( $myposts as $post ) : 
    setup_postdata( $post ); 

    $player  = get_the_author_meta('display_name');
    $cash    = get_the_author_meta('cashOnHand');
    $bank    = get_the_author_meta('bankAccount');

    $totalMoney = $cash + $bank;

    $highScores[$player] = $totalMoney; // add an entry to the array

endforeach;

asort($highScores); // sort the array

print_r($highScores); // see result

【讨论】:

  • 是的,Flip 是对的;将您的 asort 移到您的 foreach 之外。
猜你喜欢
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 2019-07-13
  • 1970-01-01
  • 2020-08-22
  • 2017-05-30
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多