Array( array( 'name' => 'title 1', 'price' => '200' ) array( 'name' => 'title 2', 'price' => '100' ) ... )
I have such an array. How can I sort it by the value of the price
key, from the smallest to the largest?
Array( array( 'name' => 'title 1', 'price' => '200' ) array( 'name' => 'title 2', 'price' => '100' ) ... )
I have such an array. How can I sort it by the value of the price
key, from the smallest to the largest?
Sort by user function: usort () .
usort($array, function($a, $b){ return ($a['price'] - $b['price']); });
$data = array ( array( 'name' => 'title 1', 'price' => 200 ), array( 'name' => 'title 2', 'price' => 100 ) ); usort ( $data, create_function ( '$a,$b', 'rerturn -($a["price"] - $b["price"]);' ) );
1) don't forget that price fields should be int, not strings (otherwise you need an explicit conversion)
2) if you need a reverse sorting order:
rerturn $a["price"] - $b["price"];
You can convert it to an array of the form:
array ('200' => 'title1', '100' => 'title2') and sort the standard php ksort function (or another one you like)
Found on the Internet:
function cmp($a, $b){ return strnatcmp($a["product_order"], $b["product_order"]); } usort($parts, "cmp");
The uasort function is intended for sorting using a user-defined function, but with preserving the array keys (as opposed to usort).
suffered for a long time with a similar problem, here is my solution:
principle:
for ($i=0; $i < count($array); $i++) { $sortkey[$i]=$array[$i]['price']; } asort($sortkey);//по возрастанию, arsort($sortkey) - по убыванию foreach ($sortkey as $key => $key) { $sorted[]=$array[$key]; }
Source: https://ru.stackoverflow.com/questions/138791/