Answers for "php sort multidimensional array by column"

PHP
9

php sort multidimensional array

function sortByAge($a, $b) {
    return $a['age'] > $b['age'];
}
$people=[
    ["age"=>54,"first_name"=>"Bob","last_name"=>"Dillion"],
    ["age"=>22,"first_name"=>"Sarah","last_name"=>"Harvard"],
    ["age"=>31,"first_name"=>"Chuck","last_name"=>"Bartowski"]
];

usort($people, 'sortByAge'); //$people is now sorted by age (ascending)
Posted by: Guest on August-06-2019
2

sort multi array php

$keys = array_column($array, 'Price');

		array_multisort($keys, SORT_ASC, $array);
	
		print_r($array);
Posted by: Guest on August-04-2020
1

php sort multidimensional array

$inventory = array(
   array("type"=>"Fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"Pork", "price"=>5.43),
);

$prices = array_column($inventory, 'price');
$inventory_prices = array_multisort($prices, SORT_DESC, $inventory);

$types = array_map(strtolower, array_column($inventory, 'type'));
$inventory_types = array_multisort($types, SORT_ASC, $inventory);
Posted by: Guest on September-04-2020
1

sort multidimensional array in php

<?php
function sortByPrice($a, $b){
	return $a['price'] > $b['price'];
}

$items = [
    ['label' => 'cake', 'name' => 'Cake', 'price' => 150],
    ['label' => 'pizza', 'name' => 'Pizza', 'price' => 250],
    ['label' => 'puff', 'name' => 'Veg Puff', 'price' => 20],
    ['label' => 'samosa', 'name' => 'Samosa', 'price' => 14]
];

//Sort by Price
usort($items, 'sortByPrice');
//print_r($items);

print "<br/> After Sort by Price printing: <br/>";
foreach($items as $item){
	print $item['name']." ".$item['price']."<br/>";
}
$newArray = array_column($items, 'price', 'name');

// find max, min, and toal sum of array
$totalExp = array_sum(array_column($items, 'price', 'name'));
$maxPrice  = max(array_column($items, 'price', 'name'));
$minPrice  = min(array_column($items, 'price', 'name'));

print "Total Expenses : ".$totalExp."<br/>";
print "What is Costly Item : ".$maxPrice.' ('.array_search($maxPrice, $newArray).")<br/>";
print "What is Cheap Item : ".$minPrice.' ('.array_search($minPrice, $newArray).")<br/>";

?>
Posted by: Guest on February-04-2021
1

php sort multidimensional array by value

function sortByOrder($a, $b) {
    return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');
Posted by: Guest on October-15-2020
0

php sort multidimensional array by value

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});
Posted by: Guest on April-18-2021

Code answers related to "php sort multidimensional array by column"

Browse Popular Code Answers by Language