Reputation: 103
I need to sort multiple array by one value in array. Unfortunately, I can not sort this inside the database. I can only get array like this.
My Array look like :
Array
(
[0] => Array
(
[id] => 10913
[name] => NAME 1
[logo_img] => 28361bd6114a32daafcf150da5ee1d33.jpeg
[has_frame] => t
[weight] => 0
)
[1] => Array
(
[id] => 10902
[name] => Name 2
[logo_img] => d0642d5efeabe8b861f2f32fa17f35b3.jpeg
[has_frame] => t
[weight] => 4
)
[2] => Array
(
[id] => 8887
[name] => Some name 3
[logo_img] => 12e47533604438bf390d69218434b630.jpeg
[has_frame] => f
[weight] => 0
)
[3] => Array
(
[id] => 49
[name] => Some name 4
[logo_img] => 5971148b049c5bb0b6e402a1de1836ef.jpeg
[has_frame] => t
[weight] => 0
)
[4] => Array
(
[id] => 10871
[name] => name2
[logo_img] => 7dcc1a6058a81b4e45de5f2274025907.jpeg
[has_frame] => t
[weight] => 0
)
[5] => Array
(
[id] => 1880
[name] => name 4
[logo_img] => dc05764ea71425a4a653b81997e7d929.jpeg
[has_frame] => f
[weight] => 0
)
[6] => Array
(
[id] => 9678
[name] => name 33
[logo_img] => 8ded98244a6928d5179398fa9d3b59bc.jpeg
[has_frame] => t
[weight] => 5
)
[7] => Array
(
[id] => 2880
[name] => name r
[logo_img] => 09876329a5ac2a84e9f83923c75e780c.jpeg
[has_frame] => f
[weight] => 0
)
[8] => Array
(
[id] => 8265
[name] => name 5
[logo_img] => 487ed3c676666e380f813f5f1a9fb040.jpeg
[has_frame] => t
[weight] => 1
)
)
I need to order this array by weight element DESC. Is it possible?
Upvotes: 0
Views: 76
Reputation: 616
//You can use `uasort` that has a comparison function that can be defined by user;
//if the name of the whole array is $array
//define a function
function compare($obj1,$obj2){
if($obj1['weight']==$obj2['weight']){
return 0;
}
return $obj1['weight']<$obj2['weight']?1:-1;
}
//the comparison operator in the function `compare` in the second return determines the order of the array elements.
//Now call the function with your array
uasort($array,'compare');
Upvotes: 1
Reputation: 1091
this is how I did it:
usort($object, 'cmp');
function cmp($a, $b)
{
return strcmp($b['weigth'], $a['weigth']); // or -> weigth
}
Upvotes: 1
Reputation: 1246
http://php.net/manual/en/function.sort.php
This lists a lot of information on sorting,
if you need to sort using the key, try
ksort($array)
Upvotes: 2