2016-09-27 89 views
1
How order an array so structured for [name] and to parity of [name] for [age] ? 

    [0] => Array 
     (
      [name] => Mary 
      [age] => 32 
     ) 

    [1] => Array 
     (
      [name] => Mary 
      [age] => 31 
     ) 

    [2] => Array 
     (
      [name] => Anna 
      [age] => 30 
     ) 

Output: 

Name | Age 
---------- 
Anna | 30 
Mary | 31 
Mary | 32 

這是代碼:如何訂購多維數組的多維數組?

function sort(&$array) { 
    function build_sorter($key) { 
    return function ($a, $b) use ($key) { 
     return strnatcmp($a[$key], $b[$key]); 
    }; 
    } 
    usort($array, build_sorter(["name"]));    
    usort($array, build_sorter(["age"]));   
} 
+0

請再具體些,並顯示您的預計產量。此外,顯示迄今爲止嘗試的代碼。 –

+0

你可以粘貼你的代碼嗎? –

+0

你想按名稱和年齡對數組進行排序? –

回答

1

您可以使用此功能

<?php 
function Func_Sort($arr, $index) { 
    $b = array(); 
    $c = array(); 
    foreach ($arr as $key => $value) { 
     $b[$key] = $value[$index]; 
    } 

    asort($b); 

    foreach ($b as $key => $value) { 
     $c[] = $arr[$key]; 
    } 

    return $c; 
} 
$activities = array (
    '1' => array(
     'name' => 'Mary', 
     'age' => 32, 

    ), 
    '2' => array(
     'name' => 'Mary', 
     'age' => 31, 
     ), 
    '3' => array(
     'name' => 'anna', 
     'age' => 30 
    ), 
); 
$sorted_act = Func_Sort($activities, 'age'); 
echo "<pre>"; 
print_r($sorted_act); 

?> 

演示鏈接:http://codepad.org/VNXbCjsT

0

需要使用:http://php.net/manual/en/function.usort.php

排序通過使用用戶定義的比較函數

實施例#4

值的數組
<?php 
    $array[0] = array('key_a' => 'z', 'key_b' => 'c'); 
    $array[1] = array('key_a' => 'x', 'key_b' => 'b'); 
    $array[2] = array('key_a' => 'y', 'key_b' => 'a'); 

    function build_sorter($key) { 
    return function ($a, $b) use ($key) { 
     return strnatcmp($a[$key], $b[$key]); 
    }; 
    } 

    usort($array, build_sorter('key_b')); 

    foreach ($array as $item) { 
    echo $item['key_a'] . ', ' . $item['key_b'] . "\n"; 
    } 

?> 
+0

在這一行返回一個「非法偏移類型」:「返回strnatcmp($ a [$ key],$ b [$ key]);」。陣列的結構如上所述。 –