2

我有一个数组如下..

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => Henry
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [name] => jack
                )
        )
    [2] => Array
        (
            [0] => Array
                (
                    [name] => Albert
                )
        )
    [3] => Array
        (
            [0] => Array
                (
                    [name] => bunny
                )
        )

我需要按名称以不区分大小写的 asc & desc 顺序对这个数组进行排序。请帮我..

4

3 回答 3

2

几年前我写了一个 php 函数来做这样的事情。

function subval_sort($a, $subkey, $reverse = false)
{
    if (!$a)
    {
        return array();
    }

    $b = array();

    foreach ($a as $k => $v)
    {
        $b[$k] = strtolower($v[$subkey]);
    }

    if ($reverse)
    {
        arsort($b);
    }
    else
    {
        asort($b);  
    }

    $c = array();

    foreach ($b as $key => $val)
    {
        $c[] = $a[$key];
    }

    return $c;
}

像这样使用它subval_sort($array, 'name')

于 2013-08-19T12:41:25.130 回答
0
$array = array(
  array('Henry'),
  array('Michael'),
  array('Steve'),
  array('Daniel'),
  array('Albert'),
);


// Comparison function
function cmp($a, $b) {
    if ($a[0] == $b[0]) {
        return 0;
    }
    return ($a[0] < $b[0]) ? -1 : 1;
}

// Array to be sorted
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);

输出:

Array
(
    [0] => Array
        (
            [0] => Henry
        )

    [1] => Array
        (
            [0] => Michael
        )

    [2] => Array
        (
            [0] => Steve
        )

    [3] => Array
        (
            [0] => Daniel
        )

    [4] => Array
        (
            [0] => Albert
        )

)
Array
(
    [4] => Array
        (
            [0] => Albert
        )

    [3] => Array
        (
            [0] => Daniel
        )

    [0] => Array
        (
            [0] => Henry
        )

    [1] => Array
        (
            [0] => Michael
        )

    [2] => Array
        (
            [0] => Steve
        )

)
于 2013-08-19T12:44:05.310 回答
0

排序功能:

使用我的自定义函数来实现它正在工作的解决方案

    function multisort (&$array, $key) {
$valsort=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
    $valsort[$ii]=$va[$key];
}
asort($valsort);
foreach ($valsort as $ii => $va) {
    $ret[$ii]=$array[$ii];
}
$array=$ret;
}

multisort($multiarr,"order");

希望这对你有帮助。

于 2013-08-19T12:41:49.687 回答