Sort a multidimensional array descending by subarray count and preserve first level keys
Using uksort
:
uksort($array, function($a, $b) { return count($b) - count($a); });
Using array_multisort
:array_multisort(array_map('count', $array), SORT_DESC, $array);
With PHP < 5.3:
function sort_cb($a, $b) {
return count($b) - count($a);
}
uksort($array, 'sort_cb');
How to Sort a Multi-dimensional Array by Value
Try a usort. If you are still on PHP 5.2 or earlier, you'll have to define a sorting function first:
function sortByOrder($a, $b) {
return $a['order'] - $b['order'];
}
usort($myArray, 'sortByOrder');
Starting in PHP 5.3, you can use an anonymous function:usort($myArray, function($a, $b) {
return $a['order'] - $b['order'];
});
With PHP 7 you can use the spaceship operator:usort($myArray, function($a, $b) {
return $a['order'] <=> $b['order'];
});
Finally, in PHP 7.4 you can clean up a bit with an arrow function:usort($myArray, fn($a, $b) => $a['order'] <=> $b['order']);
To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero - best explained below. You can also use this for sorting on sub-elements.usort($myArray, function($a, $b) {
$retval = $a['order'] <=> $b['order'];
if ($retval == 0) {
$retval = $a['suborder'] <=> $b['suborder'];
if ($retval == 0) {
$retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
}
}
return $retval;
});
If you need to retain key associations, use uasort()
- see comparison of array sorting functions in the manual. PHP Sorting Multidimensional array by number of occurrences of values in a key
The easiest solution I could come up with, is to use a second array in which we'll store the card count for each rank. We can then pass this array to the sorting function in order to get the result we want.
Here's an example of how this would look:
$cards = [...];
$ranks = [];
// Count the cards for each rank
foreach ($cards as $card) {
if (!isset($ranks[$card['Rank']])) {
$ranks[$card['Rank']] = 0;
}
$ranks[$card['Rank']]++;
}
// Sort the cards array
usort($cards, function ($a, $b) use ($ranks) {
// If the cards count is the same for the rank, compare rank
if ($ranks[$a['Rank']] == $ranks[$b['Rank']]) {
return $a['Rank'] - $b['Rank'];
}
// Compare the card count for the rank
return $ranks[$a['Rank']] - $ranks[$b['Rank']];
});
Sort a multi-dimensional array by the size of its sub-arrays
You can achieve it by utilizing usort function.
function cmp($a, $b){
return (count($b) - count($a));
}
usort($array, 'cmp');
$highest_3_sub_arrays = array_slice($array, 0, 3);
Sort multidimensional array by column value within a column
Try this...
<?php
$array = [
[
'project_id' => 1,
'earnest_money_due' => [
'value' => 1000.00,
'currency' => 'USD',
],
],
[
'project_id' => 2,
'earnest_money_due' => [
'value' => 200.00,
'currency' => 'USD',
],
],
[
'project_id' => 3,
'earnest_money_due' => [
'value' => 900.00,
'currency' => 'USD',
],
],
];
array_multisort(
array_map(
static function ($element) {
return $element['earnest_money_due']['value'];
},
$array
),
SORT_ASC,
$array
);
var_dump($array);
How do I sort a multidimensional array with stdClass Objects by values of a key?
You're almost right, but $row[$col]
tries to access the objects like an array. You want something like $row->{$col}
instead. Here's a simpler, working example:
$db = array(
0 => (object) array('name' => 'Business3'),
1 => (object) array('name' => 'Business2'),
2 => (object) array('name' => 'Business1')
);
$col = 'name';
$sort = array();
foreach ($db as $i => $obj) {
$sort[$i] = $obj->{$col};
}
$sorted_db = array_multisort($sort, SORT_ASC, $db);
print_r($db);
Outputs:Array
(
[0] => stdClass Object
(
[name] => Business1
)
[1] => stdClass Object
(
[name] => Business2
)
[2] => stdClass Object
(
[name] => Business3
)
)
How do I Sort a Multidimensional Array in PHP
You can use array_multisort()
Try something like this:
foreach ($mdarray as $key => $row) {
// replace 0 with the field's index/key
$dates[$key] = $row[0];
}
array_multisort($dates, SORT_DESC, $mdarray);
For PHP >= 5.5.0 just extract the column to sort by. No need for the loop:array_multisort(array_column($mdarray, 0), SORT_DESC, $mdarray);
Related Topics
How to Check Is Timezone Identifier Valid from Code
PHP Script to Log the Raw Data of Post
How to Use Laravel Passport with a Custom Username Column
Check If Two PHP Datetime Objects Are Set to the Same Date ( Ignoring Time )
How to Get the Root Url of the Site
Upload Progress Using Pure PHP/Ajax
How to Put Double Quotes Inside a String Within an Ajax JSON Response from PHP
SQL - Insert and Catch the Id Auto-Increment Value
How Would You Transform a Pre-Existing Web App into a Multilingual One
How to Add Filter or Hook for "Woocommerce_Add_To_Cart"
How to Select a MySQL Database to Use with Pdo in PHP
How to Force Ssl in Codeigniter
How to Add Custom Fields to Woocommerce Registration Form
How to Increase by 1 All Keys in an Array
Looping Through a Simplexml Object, or Turning the Whole Thing into an Array