【问题标题】:PHP sorty array by column and slice itPHP按列排序数组并将其切片
【发布时间】:2018-12-20 04:46:29
【问题描述】:

我正在尝试根据列值对数组进行排序:

例子:

$cats[0]['holders'] = 55;
$cats[1]['holders'] = 66;
$cats[2]['holders'] = 77;
$cats[3]['holders'] = 23;
$cats[4]['holders'] = 64;
$cats[5]['holders'] = 82;
$cats[6]['holders'] = -3;
$cats[7]['holders'] = -5;
$cats[8]['holders'] = -17;
$cats[9]['holders'] = -25;
$cats[10]['holders'] = 66;
$cats[11]['holders'] = -10;
$cats[12]['holders'] = 0;
$cats[13]['holders'] = 5;
$cats[14]['holders'] = 4;
$cats[15]['holders'] = -3;

function compareHolders($a, $b) {

    $aPoints = $a['holders'];
    $bPoints = $b['holders'];

    return strcmp($aPoints, $bPoints);

}

$cats = usort($cats, 'compareHolders');

我想获取前 5 个值和后 5 个值:

$first_5_tokens = array_slice($tokens, 0, 5, true);
print_r($first_5_tokens);

$last_5_tokens = array_slice($tokens, -5);
print_r($last_5_tokens);

这不是按“持有人”值对我的数组进行排序。我怎样才能做到这一点?谢谢!

【问题讨论】:

  • 试试return $aPoints < $bPoints;

标签: php arrays sorting slice


【解决方案1】:

您的比较函数按降序对数组进行排序,并且不要像使用它 - $cats = usort($cats, 'compareHolders');而是像使用它一样 - usort($cats, 'compareHolders');

我改变了你的功能,并这样做了。

    $cats[0]['holders'] = 55;
    $cats[1]['holders'] = 66;
    $cats[2]['holders'] = 77;
    $cats[3]['holders'] = 23;
    $cats[4]['holders'] = 64;
    $cats[5]['holders'] = 82;
    $cats[6]['holders'] = -3;
    $cats[7]['holders'] = -5;
    $cats[8]['holders'] = -17;
    $cats[9]['holders'] = -25;
    $cats[10]['holders'] = 66;
    $cats[11]['holders'] = -10;
    $cats[12]['holders'] = 0;
    $cats[13]['holders'] = 5;
    $cats[14]['holders'] = 4;
    $cats[15]['holders'] = -3;

    foreach($cats as $cat) {
        echo $cat['holders'] . "<br>";
    }

    //        function compareHolders($a, $b) {
    //
    //            $aPoints = $a['holders'];
    //            $bPoints = $b['holders'];
    //
    //            return strcmp($aPoints, $bPoints);
    //
    //        }

    function compareHolders($a, $b) {
      $a = $a['holders'];
      $b = $b['holders'];
      if ($a == $b)
        return 0;
      return ($a > $b) ? -1 : 1;
    }


    usort($cats, 'compareHolders');
    echo "<h4>After</h4>\n";
    foreach($cats as $cat) {
        echo $cat['holders'] . "<br>";
    }        

    // print_r($cats);  
    $tokens = $cats;
    echo "<h4>First Five</h4>\n";
    $first_5_tokens = array_slice($tokens, 0, 5, true);
    print_r($first_5_tokens);
    echo "<h4>Last Five</h4>\n";
    $last_5_tokens = array_slice($tokens, -5);
    print_r($last_5_tokens);        

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 2014-08-22
    • 1970-01-01
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-14
    相关资源
    最近更新 更多