开发者

Sorting Multidimensional Array by the Values

I have the following 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
          )
    )

I need to trasform the above array into the following

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
          )

    )

I have used array_multisort() but it didn't work

Is it possible to sort ?


usort like:

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


Try this one : assuming you have array in $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);


While as noted in a comment, the most efficient method in this case is to sort in the database query, here's an example of how you'd do it with array_multisort, which is a lot more efficient than usort:

$rows = $vendors = array();
while ($row = mysql_fetch_assoc($res)) {
    $vendors[] = $row['vendorname'];
    $rows[] = $row;
}
array_multisort($rows, $vendors, SORT_ASC);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜