Answers for "php object array sort by key value"

PHP
1

sort array by key value in php

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);
$price = array_column($inventory, 'price');
array_multisort($price, SORT_DESC, $inventory);
Posted by: Guest on June-03-2021
1

php sort array by object value

/**
 * A generic PHP sorting algorithm that uses `usort` and `strcmp`.
 * `usort` — Sort an array by values using a user-defined comparison function.
 * `strcmp` — Returns < 0 if param 1 is less than param 2; > 0 if param 1 is greater than param 2, and 0 if they are equal.
 */
$questions = [
  { id: 1, ordinal: 55 },
  { id: 2, ordinal: 67 },
  { id: 3, ordinal: 32 },
];

function sortByOrdinal($param1, $param2) {
    return strcmp($param1->ordinal, $param2->ordinal);
}

/* `usort` alters an existing array. */
usort($questions, "sortByOrdinal");

/**
 * $questions = [
 *   { id: 3, ordinal: 32 },
 *   { id: 1, ordinal: 55 },
 *   { id: 2, ordinal: 67 },
 * ];
 */
Posted by: Guest on September-02-2020
2

php array sort by key value

To PHP sort array by key, you should use: 
	ksort() (for ascending order) or krsort() (for descending order). 
      
To PHP sort array by value, you will need functions:
	asort() and arsort() (for ascending and descending orders).
Posted by: Guest on October-23-2020

Code answers related to "php object array sort by key value"

Browse Popular Code Answers by Language