按值排序多维数组

时间:2011-02-24 11:58:57

标签: php multidimensional-array

我有以下数组。

Array  (
        [0] => Array(
              [vendorid] => 36
              [vendorname] => Nothin' But A Muffin
              [vendorfriendlyname] => nothin-but-a-muffin
          )
        [1] => Array(
              [vendorid] => 52
              [vendorname] => Montalto Olive Grove
              [vendorfriendlyname] => montalto-olive-grove
          )
        [2] => Array(
              [vendorid] => 44
              [vendorname] => Kuki Kids
              [vendorfriendlyname] => kuki-kids
          )
        [3] => Array(
              [vendorid] => 47
              [vendorname] => pasApas
              [vendorfriendlyname] => pasapas
          )
        [4] => Array(
              [vendorid] => 89
              [vendorname] => Organic Family
              [vendorfriendlyname] => organic-family
          )
    )

我需要将上面的数组转换为以下

Array  (
        [0] => Array(
              [vendorid] => 44
              [vendorname] => Kuki Kids
              [vendorfriendlyname] => kuki-kids
          )
        [1] => Array(
              [vendorid] => 52
              [vendorname] => Montalto Olive Grove
              [vendorfriendlyname] => montalto-olive-grove
          )
        [2] => Array(
              [vendorid] => 36
              [vendorname] => Nothin' But A Muffin
              [vendorfriendlyname] => nothin-but-a-muffin
          )
        [3] => Array(
              [vendorid] => 89
              [vendorname] => Organic Family
              [vendorfriendlyname] => organic-family
          )
        [4] => Array(
              [vendorid] => 47
              [vendorname] => pasApas
              [vendorfriendlyname] => pasapas
          )

    )

我使用过array_multisort()但它没有用

可以排序吗?

3 个答案:

答案 0 :(得分:2)

usort喜欢:

    function compare($a, $b)
    {           
        return strcmp($a['vendorname'], $b['vendorname']);
    }
    usort($array, "compare");

答案 1 :(得分:0)

试试这个:假设你在$ rows中有数组

function cmp($a, $b)
{
    return strcmp($a["vendorname"], $b["vendorname"]);
}

$array = $rows; 
usort($array, "cmp");

while (list($key, $value) = each($array)) {
    $new[] =$value ;
}
echo "<pre>";
print_r($new);

答案 2 :(得分:0)

虽然如评论中所述,在这种情况下最有效的方法是对数据库查询进行排序,这是一个如何使用array_multisort进行排序的示例,这比{更高效率} {1}}:

usort