如何根据给定键在PHP中的值对关联数组进行排序?

时间:2022-10-23 12:48:44

Given this array:

鉴于这个数组:

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);

I would like to sort $inventory's elements by price to get:

我想按价格来分类$inventory的元素:

$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);

How can I do this?

我该怎么做呢?

16 个解决方案

#1


416  

You are right, the function you're looking for is array_multisort().

您是对的,您正在寻找的函数是array_multisort()。

Here's an example taken straight from the manual and adapted to your case:

这里有一个直接从手册中摘录的例子,适合你的情况:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

#2


166  

PHP 7+

As of PHP 7, this can be done concisely using usort with an anonymous function that uses the spaceship operator to compare elements.

在PHP 7中,可以使用一个匿名函数来简洁地使用这个函数来比较元素。

You can do an ascending sort like this:

你可以这样做:

usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});

Or a descending sort like this:

或者像这样的下降排序:

usort($inventory, function ($item1, $item2) {
    return $item2['price'] <=> $item1['price'];
});

To understand how this works, note that usort takes a user-provided comparison function that must behave as follows (from the docs):

要理解这是如何工作的,请注意usort采用了一个用户提供的比较函数,它必须像以下(来自文档)那样:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

如果第一个参数被认为是小于等于或大于第二个参数,则比较函数必须返回小于等于或大于零的整数。

And note also that <=>, the spaceship operator,

还要注意,<=>,宇宙飞船操作员,

returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater

如果两个操作数相等,则返回0,如果左边更大,则返回1,如果右边更大,则返回-1。

which is exactly what usort needs. In fact, almost the entire justification given for adding <=> to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it

这正是我们所需要的。实际上,在https://wiki.php.net/rfc/combined-比较运算符中添加<=>到该语言的几乎所有理由都是这样的。

makes writing ordering callbacks for use with usort() easier

使编写命令回调可以更容易地使用usort()。


PHP 5.3+

PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort to sort our array, but it's a little more verbose and harder to understand:

PHP 5.3引入了匿名函数,但还没有宇宙飞船操作员。我们仍然可以使用usort来对数组进行排序,但它有点冗长,而且更难理解:

usort($inventory, function ($item1, $item2) {
    if ($item1['price'] == $item2['price']) return 0;
    return $item1['price'] < $item2['price'] ? -1 : 1;
});

Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort has to return integers for usort to work properly:

请注意,尽管比较器处理整型值只会返回值的差值,如item2['price'] - $item1['price'],但在这种情况下,我们不能安全地这样做。这是因为价格是问题asker的例子中的浮点数,但是我们传递给usort的比较函数必须返回整数以便正常工作:

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

从比较函数中返回非整数值,例如float,将会导致回调函数返回值的一个内部转换。因此,像0.99和0.1这样的值都将被转换为0的整数值,这将会将这些值与相等的值进行比较。

This is an important trap to bear in mind when using usort in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.

在PHP 5.x中使用usort时,这是一个重要的陷阱。我最初的这个答案犯了这个错误,但是我在成千上万的观点上积累了10张选票,显然没有人注意到这个严重的错误。像我这样的笨蛋可以轻而易举地搞出比较器的功能,这正是在PHP 7中使用更容易使用的宇宙飞船操作员的原因。

#3


39  

Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

由于数组元素本身是带有字符串键的数组,所以最好的方法是定义一个自定义比较函数。这是非常快速和容易做到的。试试这个:

function invenDescSort($item1,$item2)
{
    if ($item1['price'] == $item2['price']) return 0;
    return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);

Produces the following:

产生以下:

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

#4


20  

I ended on this:

我结束了在这:

function sort_array_of_array(&$array, $subfield)
{
    $sortarray = array();
    foreach ($array as $key => $row)
    {
        $sortarray[$key] = $row[$subfield];
    }

    array_multisort($sortarray, SORT_ASC, $array);
}

Just call the function, passing the array and the name of the field of the second level array. Like:

只需调用函数,传递数组和第二级数组字段的名称。如:

sort_array_of_array($inventory, 'price');

#5


17  

While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:

虽然其他人正确地建议使用array_multisort(),但由于某种原因,似乎没有答案会承认array_column()的存在,这可以极大地简化解决方案。所以我的建议是:

array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);

#6


11  

You can use usort with anonymous function, e.g.

你可以使用匿名函数。

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });

#7


7  

$inventory = 
    array(array("type"=>"fruit", "price"=>3.50),
          array("type"=>"milk", "price"=>2.90),
          array("type"=>"pork", "price"=>5.43),
          );

function pricesort($a, $b) {
  $a = $a['price'];
  $b = $b['price'];
  if ($a == $b)
    return 0;
  return ($a > $b) ? -1 : 1;
}

usort($inventory, "pricesort");
// uksort($inventory, "pricesort");

print("first: ".$inventory[0]['type']."\n\n");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)

// foreach prints the same for usort and uksort.
foreach($inventory as $i){
  print($i['type'].": ".$i['price']."\n");
}

outputs:

输出:

first: pork

pork: 5.43
fruit: 3.5
milk: 2.9

#8


3  

Was tested on 100 000 records: Time in seconds(calculated by funciton microtime). Only for unique values on sorting key positions.

测试了10万条记录:时间以秒为单位(按运行时间计算)。只有在排序关键位置时才有唯一的值。

Solution of function of @Josh Davis: Spended time: 1.5768740177155

@Josh Davis的函数解:spend时间:1.5768740177155。

Mine solution: Spended time: 0.094044923782349

我的解决方案:spend time: 0.094044923782349。

Solution:

解决方案:

function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = array();
    foreach ($data as $key => $value)
        $ordered[$value[$sortKey]] = $value;

    ksort($ordered, $sort_flags);

    return array_values($ordered); *// array_values() added for identical result with multisort*
}

#9


1  

You might try to define your own comparison function and then use usort.

您可以尝试定义自己的比较函数,然后使用usort。

#10


0  

//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);

//result

Array
(
[2] => Array
    (
        [type] => pork
        [price] => 5.43
    )

[0] => Array
    (
        [type] => fruit
        [price] => 3.5
    )

[1] => Array
    (
        [type] => milk
        [price] => 2.9
    )

)

#11


0  

This function is re-usable:

这个函数是可重用:

function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
    uasort($array, function($a, $b) use($key, $callback) {
        return call_user_func($callback, $a[$key], $b[$key]);
    });
}

It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.

默认情况下,它可以很好地处理字符串值,但是如果所有的值都是数字,那么就必须将回调函数替换为数字比较函数。

#12


0  

Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.

完整的动态函数,我在这里跳转到关联数组排序,并在http://php.net/manual/en/function.sort.php中找到了这个神奇的函数。这个函数是非常动态的,以指定的键在升序和降序排序。

Simple function to sort an array by a specific key. Maintains index association

用一个特定的键对数组进行排序的简单函数。维护索引协会

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

#13


-1  

$arr1 = array(

    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$result1 = array_msort($arr1, array('name'=>SORT_DESC);

$result2 = array_msort($arr1, array('cat'=>SORT_ASC);

$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));


function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
    $colarr[$col] = array();
    foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}

$eval = 'array_multisort(';

foreach ($cols as $col => $order) {
    $eval .= '$colarr[\''.$col.'\'],'.$order.',';
}

$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
    foreach ($arr as $k => $v) {
        $k = substr($k,1);
        if (!isset($ret[$k])) $ret[$k] = $array[$k];
        $ret[$k][$col] = $array[$k][$col];
    }
}
return $ret;


} 

#14


-1  

  <?php

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);



function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>

the simple solution :)

简单解决办法:)

the output is,

输出,

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

#15


-2  

try this:

试试这个:

asort($array_to_sort, SORT_NUMERIC);

for reference see this: http://php.net/manual/en/function.asort.php

请参阅http://php.net/manual/en/function.asort.php。

see various sort flags here: http://www.php.net/manual/en/function.sort.php

在这里可以看到各种类型的标志:http://www.php.net/manual/en/function.sort.php。

#16


-2  

From Sort an array of associative arrays by value of given key in php:

根据php中给定键的值对关联数组进行排序:

$array = array('0'=>array('price'=>'1000.50','product'=>'test1'),
          '1'=>array('price'=>'8800.50','product'=>'test2'),
          '2'=>array('price'=>'200.0','product'=>'test3'));
    function cmp($a, $b)
    {
    $p1 = $a['price'];
    $p2 = $b['price'];
    return (float)$p1 > (float)$p2;
    }
    @uasort($array, "cmp");

#1


416  

You are right, the function you're looking for is array_multisort().

您是对的,您正在寻找的函数是array_multisort()。

Here's an example taken straight from the manual and adapted to your case:

这里有一个直接从手册中摘录的例子,适合你的情况:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

#2


166  

PHP 7+

As of PHP 7, this can be done concisely using usort with an anonymous function that uses the spaceship operator to compare elements.

在PHP 7中,可以使用一个匿名函数来简洁地使用这个函数来比较元素。

You can do an ascending sort like this:

你可以这样做:

usort($inventory, function ($item1, $item2) {
    return $item1['price'] <=> $item2['price'];
});

Or a descending sort like this:

或者像这样的下降排序:

usort($inventory, function ($item1, $item2) {
    return $item2['price'] <=> $item1['price'];
});

To understand how this works, note that usort takes a user-provided comparison function that must behave as follows (from the docs):

要理解这是如何工作的,请注意usort采用了一个用户提供的比较函数,它必须像以下(来自文档)那样:

The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.

如果第一个参数被认为是小于等于或大于第二个参数,则比较函数必须返回小于等于或大于零的整数。

And note also that <=>, the spaceship operator,

还要注意,<=>,宇宙飞船操作员,

returns 0 if both operands are equal, 1 if the left is greater, and -1 if the right is greater

如果两个操作数相等,则返回0,如果左边更大,则返回1,如果右边更大,则返回-1。

which is exactly what usort needs. In fact, almost the entire justification given for adding <=> to the language in https://wiki.php.net/rfc/combined-comparison-operator is that it

这正是我们所需要的。实际上,在https://wiki.php.net/rfc/combined-比较运算符中添加<=>到该语言的几乎所有理由都是这样的。

makes writing ordering callbacks for use with usort() easier

使编写命令回调可以更容易地使用usort()。


PHP 5.3+

PHP 5.3 introduced anonymous functions, but doesn't yet have the spaceship operator. We can still use usort to sort our array, but it's a little more verbose and harder to understand:

PHP 5.3引入了匿名函数,但还没有宇宙飞船操作员。我们仍然可以使用usort来对数组进行排序,但它有点冗长,而且更难理解:

usort($inventory, function ($item1, $item2) {
    if ($item1['price'] == $item2['price']) return 0;
    return $item1['price'] < $item2['price'] ? -1 : 1;
});

Note that although it's fairly common for comparators dealing with integer values to just return the difference of the values, like $item2['price'] - $item1['price'], we can't safely do that in this case. This is because the prices are floating point numbers in the question asker's example, but the comparison function we pass to usort has to return integers for usort to work properly:

请注意,尽管比较器处理整型值只会返回值的差值,如item2['price'] - $item1['price'],但在这种情况下,我们不能安全地这样做。这是因为价格是问题asker的例子中的浮点数,但是我们传递给usort的比较函数必须返回整数以便正常工作:

Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.

从比较函数中返回非整数值,例如float,将会导致回调函数返回值的一个内部转换。因此,像0.99和0.1这样的值都将被转换为0的整数值,这将会将这些值与相等的值进行比较。

This is an important trap to bear in mind when using usort in PHP 5.x! My original version of this answer made this mistake and yet I accrued ten upvotes over thousands of views apparently without anybody noticing the serious bug. The ease with which lackwits like me can screw up comparator functions is precisely the reason that the easier-to-use spaceship operator was added to the language in PHP 7.

在PHP 5.x中使用usort时,这是一个重要的陷阱。我最初的这个答案犯了这个错误,但是我在成千上万的观点上积累了10张选票,显然没有人注意到这个严重的错误。像我这样的笨蛋可以轻而易举地搞出比较器的功能,这正是在PHP 7中使用更容易使用的宇宙飞船操作员的原因。

#3


39  

Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

由于数组元素本身是带有字符串键的数组,所以最好的方法是定义一个自定义比较函数。这是非常快速和容易做到的。试试这个:

function invenDescSort($item1,$item2)
{
    if ($item1['price'] == $item2['price']) return 0;
    return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);

Produces the following:

产生以下:

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

#4


20  

I ended on this:

我结束了在这:

function sort_array_of_array(&$array, $subfield)
{
    $sortarray = array();
    foreach ($array as $key => $row)
    {
        $sortarray[$key] = $row[$subfield];
    }

    array_multisort($sortarray, SORT_ASC, $array);
}

Just call the function, passing the array and the name of the field of the second level array. Like:

只需调用函数,传递数组和第二级数组字段的名称。如:

sort_array_of_array($inventory, 'price');

#5


17  

While others have correctly suggested the use of array_multisort(), for some reason no answer seems to acknowledge the existence of array_column(), which can greatly simplify the solution. So my suggestion would be:

虽然其他人正确地建议使用array_multisort(),但由于某种原因,似乎没有答案会承认array_column()的存在,这可以极大地简化解决方案。所以我的建议是:

array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);

#6


11  

You can use usort with anonymous function, e.g.

你可以使用匿名函数。

usort($inventory, function ($a, $b) { return strnatcmp($a['price'], $b['price']); });

#7


7  

$inventory = 
    array(array("type"=>"fruit", "price"=>3.50),
          array("type"=>"milk", "price"=>2.90),
          array("type"=>"pork", "price"=>5.43),
          );

function pricesort($a, $b) {
  $a = $a['price'];
  $b = $b['price'];
  if ($a == $b)
    return 0;
  return ($a > $b) ? -1 : 1;
}

usort($inventory, "pricesort");
// uksort($inventory, "pricesort");

print("first: ".$inventory[0]['type']."\n\n");
// for usort(): prints milk (item with lowest price)
// for uksort(): prints fruit (item with key 0 in the original $inventory)

// foreach prints the same for usort and uksort.
foreach($inventory as $i){
  print($i['type'].": ".$i['price']."\n");
}

outputs:

输出:

first: pork

pork: 5.43
fruit: 3.5
milk: 2.9

#8


3  

Was tested on 100 000 records: Time in seconds(calculated by funciton microtime). Only for unique values on sorting key positions.

测试了10万条记录:时间以秒为单位(按运行时间计算)。只有在排序关键位置时才有唯一的值。

Solution of function of @Josh Davis: Spended time: 1.5768740177155

@Josh Davis的函数解:spend时间:1.5768740177155。

Mine solution: Spended time: 0.094044923782349

我的解决方案:spend time: 0.094044923782349。

Solution:

解决方案:

function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
{
    if (empty($data) or empty($sortKey)) return $data;

    $ordered = array();
    foreach ($data as $key => $value)
        $ordered[$value[$sortKey]] = $value;

    ksort($ordered, $sort_flags);

    return array_values($ordered); *// array_values() added for identical result with multisort*
}

#9


1  

You might try to define your own comparison function and then use usort.

您可以尝试定义自己的比较函数,然后使用usort。

#10


0  

//Just in one line custom function
function cmp($a, $b)
{
return (float) $a['price'] < (float)$b['price'];
}
@uasort($inventory, "cmp");
print_r($inventory);

//result

Array
(
[2] => Array
    (
        [type] => pork
        [price] => 5.43
    )

[0] => Array
    (
        [type] => fruit
        [price] => 3.5
    )

[1] => Array
    (
        [type] => milk
        [price] => 2.9
    )

)

#11


0  

This function is re-usable:

这个函数是可重用:

function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
    uasort($array, function($a, $b) use($key, $callback) {
        return call_user_func($callback, $a[$key], $b[$key]);
    });
}

It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.

默认情况下,它可以很好地处理字符串值,但是如果所有的值都是数字,那么就必须将回调函数替换为数字比较函数。

#12


0  

Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.

完整的动态函数,我在这里跳转到关联数组排序,并在http://php.net/manual/en/function.sort.php中找到了这个神奇的函数。这个函数是非常动态的,以指定的键在升序和降序排序。

Simple function to sort an array by a specific key. Maintains index association

用一个特定的键对数组进行排序的简单函数。维护索引协会

<?php

function array_sort($array, $on, $order=SORT_ASC)
{
    $new_array = array();
    $sortable_array = array();

    if (count($array) > 0) {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                foreach ($v as $k2 => $v2) {
                    if ($k2 == $on) {
                        $sortable_array[$k] = $v2;
                    }
                }
            } else {
                $sortable_array[$k] = $v;
            }
        }

        switch ($order) {
            case SORT_ASC:
                asort($sortable_array);
            break;
            case SORT_DESC:
                arsort($sortable_array);
            break;
        }

        foreach ($sortable_array as $k => $v) {
            $new_array[$k] = $array[$k];
        }
    }

    return $new_array;
}

$people = array(
    12345 => array(
        'id' => 12345,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    12346 => array(
        'id' => 12346,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    12347 => array(
        'id' => 12347,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname

#13


-1  

$arr1 = array(

    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$result1 = array_msort($arr1, array('name'=>SORT_DESC);

$result2 = array_msort($arr1, array('cat'=>SORT_ASC);

$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));


function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
    $colarr[$col] = array();
    foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}

$eval = 'array_multisort(';

foreach ($cols as $col => $order) {
    $eval .= '$colarr[\''.$col.'\'],'.$order.',';
}

$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
    foreach ($arr as $k => $v) {
        $k = substr($k,1);
        if (!isset($ret[$k])) $ret[$k] = $array[$k];
        $ret[$k][$col] = $array[$k][$col];
    }
}
return $ret;


} 

#14


-1  

  <?php

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);



function myfunc($a,$b){
return strnatcmp($a['price'],$b['price']);
}
$result=usort ($inventory,"myfunc");?>
<pre><?php print_r(array_reverse($inventory)); ?></pre>

the simple solution :)

简单解决办法:)

the output is,

输出,

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

#15


-2  

try this:

试试这个:

asort($array_to_sort, SORT_NUMERIC);

for reference see this: http://php.net/manual/en/function.asort.php

请参阅http://php.net/manual/en/function.asort.php。

see various sort flags here: http://www.php.net/manual/en/function.sort.php

在这里可以看到各种类型的标志:http://www.php.net/manual/en/function.sort.php。

#16


-2  

From Sort an array of associative arrays by value of given key in php:

根据php中给定键的值对关联数组进行排序:

$array = array('0'=>array('price'=>'1000.50','product'=>'test1'),
          '1'=>array('price'=>'8800.50','product'=>'test2'),
          '2'=>array('price'=>'200.0','product'=>'test3'));
    function cmp($a, $b)
    {
    $p1 = $a['price'];
    $p2 = $b['price'];
    return (float)$p1 > (float)$p2;
    }
    @uasort($array, "cmp");