本文介绍了根据内部数组中的值对PHP多维数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据内部数组中的特定值对我的PHP哈希表进行排序.数据结构如下:

I'm trying to sort my PHP hashtable based on a specific value in the inner array. The data structure looks like this:

print_r($mydata);

Array(
[0] => Array
    (
        [type] => suite
        [name] => A-Name
    )
[1] => Array
    (
        [type] => suite
        [name] => C-Name
    )
[2] => Array
    (
        [type] => suite
        [name] => B-Name
    )
)

我尝试了 ksort sort usort ,但似乎没有任何效果.我正在尝试根据名称键向下两级进行排序.

I've tried ksort, sort, usort but nothing seems to work. I'm trying to sort based on the name key two-levels down.

这是我使用usort的尝试:

This was my attempt using usort:

function cmp($a, $b) {
    return $b['name'] - $a['name'];
}

usort($mydata, "cmp");

是否有一种简单的方法可以做到这一点,或者我需要编写自定义排序功能?

Is there an easy way to do this or do I need to write a custom sort function?

推荐答案

思考,更加实用实用 http://php.net/manual/en/function.sort.php

Thinking,more useful and practicalhttp://php.net/manual/en/function.sort.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;
}

使用方法

 $list = array(
   array( 'type' => 'suite', 'name'=>'A-Name'),
   array( 'type' => 'suite', 'name'=>'C-Name'),
   array( 'type' => 'suite', 'name'=>'B-Name')
 );

$list = array_sort($list, 'name', SORT_ASC);

array(3) { [0]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "A-Name"    } [2]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "B-Name" } [1]=> array(2) { ["type"]=> string(5) "suite" ["name"]=> string(6) "C-Name" } }

这篇关于根据内部数组中的值对PHP多维数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 14:13