PHP按列排序数组并将其切片

时间:2018-07-12 04:41:16

标签: php arrays sorting slice

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

示例:

$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);

这不是按“ holder”值对我排序数组。我怎样才能做到这一点?谢谢!

1 个答案:

答案 0 :(得分: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);