二維陣列排序

PHP有提供

array_multisort($arrays['id'], SORT_ASC, SORT_STRING);

指定陣列的key做排序

// 資料 
$sort=[['name'=>'henry','value'=>100],['name'=>'jeason','value'=>90],
      ['name'=>'impact','value'=>20],['name'=>'mistake','value'=>50],
      ['name'=>'bebe','value'=>100],['name'=>'toyz','value'=>94]];


// print_r($sort);

function array_orderby()
{
    $args = func_get_args();
    $data = array_shift($args);
    foreach ($args as $n => $field) {
        if (is_string($field)) {
            $tmp = array();
            foreach ($data as $key => $row)
                $tmp[$key] = $row[$field];
            $args[$n] = $tmp;
            }
    }
    $args[] = &$data;
    call_user_func_array('array_multisort', $args);
    return array_pop($args);
}


// 依照value 進行排序
$sorted = array_orderby($sort, 'value', SORT_DESC);

// 顯示結果
echo '<pre>',print_r($sorted),'</pre>';

排序後的結果


Array
(
    [0] => Array
        (
            [name] => bebe
            [value] => 100
        )

    [1] => Array
        (
            [name] => henry
            [value] => 100
        )

    [2] => Array
        (
            [name] => toyz
            [value] => 94
        )

    [3] => Array
        (
            [name] => jeason
            [value] => 90
        )

    [4] => Array
        (
            [name] => mistake
            [value] => 50
        )

    [5] => Array
        (
            [name] => impact
            [value] => 20
        )
)

results matching ""

    No results matching ""