Fl0R1D3R
Fl0R1D3R

Reputation: 892

How to sort an item of an multidimimensional array in php?

I have an array in this form:

$parray[]=array('item_id'=>$rs->fields['item_id'], 
                'item_name'=>$rs->fields['item_name'],
                'item_count' =>$cs->fields['item_count'],
                'item_link'=>$rs->fields['item_link']);

and in a loop i set the values. so, i have them in $parray[0], $parray[1]...

now, how do I sort this array on item_count ?

for example:

$parray[0] = 0, "hello", 5, www.abc.abc
$parray[1] = 1, "hello2", 7, www.abc.abcab
$parray[2] = 2, "hello1", 8, www.abc.abca
$parray[3] = 3, "hello3", 2, www.abc.abcaaa

result should be

$parray[0] = 2, "hello1", 8, www.abc.abca
$parray[1] = 0, "hello", 5, www.abc.abc
$parray[2] = 1, "hello2", 3, www.abc.abcab
$parray[3] = 3, "hello3", 2, www.abc.abcaaa

how could i manage that ?

thanks

Upvotes: 0

Views: 89

Answers (1)

Expedito
Expedito

Reputation: 7795

usort($parray, function ($a, $b){
    return $b['item_count'] - $a['item_count'];
});
print_r($parray);

Here's an alternative way:

$sub = array();
foreach ($parray as $item) {
    $sub[] = $item['item_count'];
}
array_multisort($sub, SORT_DESC, $parray);
print_r($parray);

Upvotes: 1

Related Questions