按字母数字(第一个数字,然后是字母)按值对多维数组进行排序


Sorting multidimensional array by values alphanumerically (first numbers, then letters)

我有这个$countries数组:

Array ( [0] => 2013 Germany [1] => country [2] => Berlin [3] => Beer)
Array ( [0] => 2012 Italy [1] => country  [2] => Rome [3] => Wine  )
Array ( [0] => 2013 Germany [1] => country  [2] => Munich [3] => Beer )
Array ( [0] => 2013 Germany [1] => country  [2] => Dusseldorf [3] => Beer )
Array ( [0] => 2013 Italy [1] => country  [2] => Venice [3] => Wine )
Array ( [0] => 2013 Russia ....) etc

我想按年份的升序对其进行排序,这样我就会有类似的东西

Array ( [0] => 2012 Italy [1] => country  [2] => Rome [3] => Wine  )
Array ( [0] => 2013 Germany [1] => country [2] => Berlin [3] => Beer)
Array ( [0] => 2013 Germany [1] => country  [2] => Munich [3] => Beer )....

我已经尝试过排序asortnatsort,但到目前为止它们似乎都不起作用。

有什么想法吗?

foreach ($countries as $key => $row) {
    $year[$key]  = $row[0];
}

array_multisort($year, SORT_ASC, $countries);

您必须按函数array_multisort多维数组进行排序。

首先,您必须准备排序数组,然后应用排序本身:

$sortArr = array();
// prepare the sorting array
foreach ($arrayToSort as $row) {
  $sortArr[] = $row[0];  // put there the year value
}
// sorting - first param is helper array, then constant with sorting direction, third param is array you wish to sort
array_multisort($sortArr, SORT_ASC, $arrayToSort);

尝试使用 usort。查看文档中的示例 #2 (http://www.php.net/manual/en/function.usort.php):

示例 #2 usort() 示例使用多维数组

<?php
function cmp($a, $b)
{
    return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
while (list($key, $value) = each($fruits)) {
    echo "'$fruits[$key]: " . $value["fruit"] . "'n";
}
?>

对多维数组进行排序时,$a 和 $b 包含引用 到数组的第一个索引。上面的示例将输出:

$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons

我已经复制了你的数组,使其没有键值,如下所示:

$test = array (Array (  '2013 Germany',  'country',  'Berlin ', 'Beer'),
Array (  '2012 Italy' , 'country'  , 'Rome',  'Wine'  ),
Array (  '2013 Germany' , 'country' ,  'Munich' ,  'Beer' ),
Array (  '2013 Germany',  'country' ,  'Dusseldorf',  'Beer' ),
Array (  '2013 Italy' , 'country' ,  'Venice' , 'Wine' )
);

之后我使用了:

asort($test);
$test = array_values($test);    
print_r($test);

输出是:

Array
(
    [0] => Array
        (
            [0] => 2012 Italy
            [1] => country
            [2] => Rome
            [3] => Wine
        )
    [1] => Array
        (
            [0] => 2013 Germany
            [1] => country
            [2] => Berlin 
            [3] => Beer
        )
    [2] => Array
        (
            [0] => 2013 Germany
            [1] => country
            [2] => Dusseldorf
            [3] => Beer
        )
    [3] => Array
        (
            [0] => 2013 Germany
            [1] => country
            [2] => Munich
            [3] => Beer
        )
    [4] => Array
        (
            [0] => 2013 Italy
            [1] => country
            [2] => Venice
            [3] => Wine
        )
)

希望你正在寻找这个。