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?

  • @chuikoff; To format a code, select it with the mouse and click on the button 101010 of the editor. - Deleted
  • By the way, you can use the array_multisort function, for more details, see the article… - IntellectSys

6 answers 6

Sort by user function: usort () .

 usort($array, function($a, $b){ return ($a['price'] - $b['price']); }); 
  • And how to forget this feature in the smarty template? - chuikoff
  • Is it worth doing in the submission? Transfer the already sorted array, or sort it with JavaScript. In general, if you really want: {php} / * PHP code * / {/ php} - xEdelweiss
 $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:


          • we build another array "2" where the key of the new array = the key of the old one, and the value itself = the value by which we want to sort;
          • sort the new array "2" PRESERVING KEYS (asort, arsort);
          • well, then we build another array "3" on the basis of array "2" - we pass through array "2" and in the course we insert into array "3" a subarray "of array" 1 "by key of array" 2 ";
          • array "3" is our sorted one.
           for ($i=0; $i < count($array); $i++) { $sortkey[$i]=$array[$i]['price']; } asort($sortkey);//по возрастанию, arsort($sortkey) - по убыванию foreach ($sortkey as $key => $key) { $sorted[]=$array[$key]; } 
          • As a result, you will have created 2 arrays more than in the responses of other participants. Please tell us what your algorithm is better. - therainycat