Home >Backend Development >PHP Tutorial >多维数组排序

多维数组排序

WBOY
WBOYOriginal
2016-06-06 20:21:171091browse

我有个数组

<code>[
    ["id"=>3],
    ["id"=>1], 
    ["id"=>2]
]
</code>

现在要按照id的升序排列

<code>[
    ["id"=>1],
    ["id"=>2], 
    ["id"=>3]
]
</code>

我该怎么做呢?最好借用内置函数。

回复内容:

我有个数组

<code>[
    ["id"=>3],
    ["id"=>1], 
    ["id"=>2]
]
</code>

现在要按照id的升序排列

<code>[
    ["id"=>1],
    ["id"=>2], 
    ["id"=>3]
]
</code>

我该怎么做呢?最好借用内置函数。

http://php.net/manual/en/function.usort.php

<code>usort($arr, 'cmp');
function cmp($a, $b)
{
    if ($a['id'] == $b['id']) {
        return 0;
    }
    return ($a['id'] </code>

如果能确定value都是int型的话

<code>usort($arr, 'cmp');
function cmp($a, $b)
{
    return $a['id'] - $b['id'];
}</code>

<code>$data=当前数组;
foreach($data as $d){
    $arr[$data['id']]=$d;
}
print_r($arr);
</code>

你看下吧,写个函数,通用的,http://blog.csdn.net/igo9go_zq/article/details/48138405

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn