Sort Multi-Dimensional Array by Specific Key

Sort multi-dimensional array by specific key

You would use usort() - http://php.net/usort

My suggestion would be:

    function cmp($a, $b)
{
return strcmp($a->display_name, $b->display_name);
}

usort($blogusers, "cmp");

foreach ($blogusers as $bloguser)
{
...

php sort multidimensional array by specific key

Use this:

foreach($myArray as $emailAddressKey=>$datesArray){
krsort($myArray[$emailAddressKey]);
}
print_r($myArray);

or (but i prefer the first option)

foreach($myArray as &$value){
krsort($value);
// this works only if $value is passed by reference. If it's not,
// it will update $value, but not $myArray[$key] as $value is only
// a local variable.
}
print_r($myArray);

This is the sorting method:

krsort — Sort an array by key in reverse order

bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

See a working example here: https://3v4l.org/pok2e

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 - How to sort multidimensional array by Key?

Working demo.

You can use array_multisort to achieve your requirement.

$keys = [];
foreach($arr as $k => $item){
$keys[] = key($item);
}
array_multisort($keys, SORT_NATURAL, $arr);

array_multisort — Sort multiple or multi-dimensional arrays

SORT_NATURAL - compare items as strings using "natural ordering" like natsort().

Sort multidimensional array by specific key value

Try with this:

<?php 

$arr = array();

$arr["2022-02-28"] = [
array("post_id"=>"3656", "time"=>"16:05", "priority"=>"0"),
array("post_id"=>"4856", "time"=>"13:05", "priority"=>"3")];
$arr["2022-03-01"] = [
array("post_id"=>"3656", "time"=>"16:05", "priority"=>"0"),
array("post_id"=>"3636", "time"=>"13:05", "priority"=>"1")
];

foreach($arr as $key => $value){

usort($value, function($a,$b){
return strtotime($a["time"])>strtotime($b["time"]);
});

$arr[$key] = $value;

}

echo "<pre>";
var_dump($arr);
echo "</pre>";

Output:

array(2) {
["2022-02-28"]=>
array(2) {
[0]=>
array(3) {
["post_id"]=>
string(4) "4856"
["time"]=>
string(5) "13:05"
["priority"]=>
string(1) "3"
}
[1]=>
array(3) {
["post_id"]=>
string(4) "3656"
["time"]=>
string(5) "16:05"
["priority"]=>
string(1) "0"
}
}
["2022-03-01"]=>
array(2) {
[0]=>
array(3) {
["post_id"]=>
string(4) "3636"
["time"]=>
string(5) "13:05"
["priority"]=>
string(1) "1"
}
[1]=>
array(3) {
["post_id"]=>
string(4) "3656"
["time"]=>
string(5) "16:05"
["priority"]=>
string(1) "0"
}
}

PHP - sort multidimensional array by key

You can shorten your loop with:

ksort($array);
foreach($array as &$value) {
ksort($value);
}

Or use array_walk:

ksort($array);
array_walk($array, 'ksort');

Naturally sort a multi-dimensional array by key

Something simpler. Extract the array keys and sort those, sorting the original by that:

array_multisort(array_keys($array), SORT_NATURAL, $array);

With case insensitivity:

array_multisort(array_keys($array), SORT_NATURAL | SORT_FLAG_CASE, $array);

Sorting by key in a multidimensional array with php

Generic solution to sort arrays of arrays with multiple keys

Based on my answer to this question, here is a very generic solution that you can use in lots of situations.

Limitation: Requires PHP >= 5.3 to work, due to the presence of anonymous functions.

New and improved, now with descending sort support

function make_comparer() {
$criteriaNames = func_get_args();
$comparer = function($first, $second) use ($criteriaNames) {
// Do we have anything to compare?
while(!empty($criteriaNames)) {
// What will we compare now?
$criterion = array_shift($criteriaNames);

// Used to reverse the sort order by multiplying
// 1 = ascending, -1 = descending
$sortOrder = 1;
if (is_array($criterion)) {
$sortOrder = $criterion[1] == SORT_DESC ? -1 : 1;
$criterion = $criterion[0];
}

// Do the actual comparison
if ($first[$criterion] < $second[$criterion]) {
return -1 * $sortOrder;
}
else if ($first[$criterion] > $second[$criterion]) {
return 1 * $sortOrder;
}

}

// Nothing more to compare with, so $first == $second
return 0;
};

return $comparer;
}

How to use it

To sort by year ascending:

uasort($array, make_comparer('Year'));

To sort by year ascending, then by month ascending:

uasort($array, make_comparer('Year', 'Month'));

To sort by year descending, then by month ascending:

uasort($array, make_comparer(array('Year', SORT_DESC), 'Month'));

This last one is what you 're after.

PHP: Sort Multidimensional Array Based on Term in relation to a value of a key

Here's a function that I think will do what you want. I've presumed you want to find the value of $term at the beginning of a word. This code extracts any keyword in the title which includes $term and then sorts based on whether the keyword was found, followed by the ordering of the keyword, or if they are both the same, on the title.

$term = 'geo';
usort($data, function ($a, $b) use ($term) {
// find the term in first entry
$t1 = preg_match("/^.*?\b($term\w*)\b.*\$/i", $a['result_title'], $matches) ? $matches[1] : '';
// find the term in second entry
$t2 = preg_match("/^.*?\b($term\w*)\b.*\$/i", $b['result_title'], $matches) ? $matches[1] : '';
// check if the terms were found
if ($t1 == '' && $t2 != '') return 1;
if ($t1 != '' && $t2 == '') return -1;
// found in both - if not the same, just sort on the keyword
if ($t1 != $t2) return strcmp($t1, $t2);
// found the same keyword, sort on the whole title
return strcmp($a['result_title'], $b['result_title']);
});

Since the output is long (it is what you asked for) I've omitted it but I've made a demo on 3v4l.org.



Related Topics



Leave a reply



Submit