Answers for "sort array values with keys php"

PHP
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
10

php sort array by key

$weight = [
    'Pete' => 75, 
    'Benjamin' => 89,
    'Jonathan' => 101
  ];  	
  ksort($weight);
Posted by: Guest on December-04-2019
2

php sort array of array by key

$inventory = [
	['price' => 10.99, 'product' => 'foo 1'],
    ['price' => 5.99, 'product' => 'foo 2'],
  	['price' => 100, 'product' => 'foo 3'],
  
];

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);
Posted by: Guest on August-25-2020
0

array sort php

<?php

$fruits = array("lemon", "orange", "banana", "apple");
sort($fruits);
foreach ($fruits as $key => $val) {
    echo $val;
}
/*
OUTPUT:
apple
banana
lemon
orange
*/
?>
Posted by: Guest on May-14-2020

Browse Popular Code Answers by Language