按多个数组排序数据

时间:2011-03-31 15:47:39

标签: php arrays sorting multidimensional-array

我有一个这样的数组:

   $B = array(
    array("firstnam" =>"A", "lastname"=>"D", "grade" => "k1", "score" => 50),
    array("firstnam" =>"B", "lastname"=>"C", "grade" => "k4", "score" => 20),
    array("firstnam" =>"C", "lastname"=>"B", "grade" => "k3", "score" => 10),
    array("firstnam" =>"D", "lastname"=>"A", "grade" => "k2", "score" => 80)
);

2 个答案:

答案 0 :(得分:1)

如果您尝试按h4排序h1-3,请尝试以下操作:

array_multisort($h4, SORT_NUMERIC, SORT_ASC, $h3, SORT_NUMERIC, SORT_ASC, $h2, SORT_NUMERIC, SORT_ASC, $h1, SORT_NUMERIC, SORT_ASC);

如果这不是您想要的,请尝试重新描述您的问题。

答案 1 :(得分:0)

public function sortByHeader($columns, $sortOrder=1/* or -1 for desc */) {
    $this->sort_columns = $columns;
    $this->sort_order = $sortOrder;
    uasort($this->data, array($this, "cmp"));
}

public function cmp($a, $b) {
    foreach ($this->sort_columns as $column) {
        // It's also important to check datatypes if you have string and it in diff columns
        if ($a[$column] > $b[$column]) {
            return $this->sort_order;
        }
        if ($a[$column] < $b[$column]) {
            return -$this->sort_order;
        }
    }
    return 0;
}

uasort允许使用自定义回调对数据进行排序。请参阅PHP man以供参考