Sort Multidimensional array by two variables - PHP - php

I need to sort my array php by a key value. my array:
Array
(
[1430039342393636453] => Array
(
[0] => Array
(
[thrid] => 1430039342393636453
[uid] => 19748
[flag] => 1
[timestamp] => 1363791789
[date] => Mar 20
[content_preview] =>
[content] =>
)
)
[1430750471744336569] => Array
(
[0] => Array
(
[thrid] => 1430750471744336569
[uid] => 19870
[flag] => 1
[timestamp] => 1364469959
[date] => Mar 28
[content_preview] =>
[content] =>
)
[1] => Array
(
[thrid] => 1430750471744336569
[uid] => 19874
[flag] => 1
[timestamp] => 1364472417
[date] => Mar 28
[content_preview] =>
[content] =>
)
)
I need to sort by timestamp the main array and also the childs arrays.
Any suggesitons?

Use asort to sort associative arrays.
Related S.O. Post:
Sorting an associative array in PHP

Try something like:
private function sort($sort) {
foreach($sort as &$arr) { //use a reference because usort uses references to manipulate your array.
//if you don't pass by reference you'll never see the sort
usort($arr, function($a, $b) { return $a['timestamp'] - $b['timestamp'];
}
usort($sort, function($a, $b) { return key($a) - key($b); }
return $sort;
}

Related

Sort array by date

My array has an array for each field (i.e date, name, etc.). How do I sort the array by date? Should I create another array? Can I use sort or unsort here. If yes, how? Here is my array:
Array
(
[date] => Array
(
[0] => 03/11/2019
[1] => 03/19/2019
[2] => 03/15/2019
[3] => 12/15/2018
)
[name] => Array
(
[0] => Lowa
[1] => Stephanie
[2] => Allan
[3] => Joffer
)
[number] => Array
(
[0] => 178989898
[1] => 111111111
[2] => 222222222
[3] => 333333333
)
[unit] => Array
(
[0] => HR
[1] => VPP
[2] =>
[3] => OAT
)
[department] => Array
(
[0] => Chemistry
[1] => IT
[2] => Lab
[3] => Contractor
)
)
At the end, my first element will be:
03/19/2019 Stephanie 111111111 VPP IT
I think your data can be better organized:
$newArr = Array
(
[0] => Array
(
[date] => 03/11/2019
[name] => Lowa
[number] => 178989898
[unit] => HR
[department] => Chemistry
)
[1] => Array
(
[date] => 03/19/2019
[name] => Stephanie
[number] => 111111111
[unit] => VPP
[department] => IT
)
[2] => Array
(
[date] => 03/15/2019
[name] => Allan
[number] => 222222222
[unit] =>
[department] => Lab
)
[3] => Array
(
[date] => 12/15/2018
[name] => Joffer
[number] => 333333333
[unit] => OAT
[department] => Contractor
)
);
Then, you can simply sort it by:
function cmp($a, $b) {
if ($a["date"] == $b["date"]) return 0;
return ($a["date"] < $b["date"]) ? -1 : 1;
}
usort($newArr, "cmp");
Please be warned that dates in the format "Month/Day/Year" ar not alphabetically sortable.
You definitively should use a Year/Month/Day format for your dates, or write a more specific cmp() function...
UPDATE: To answer OP's question in comment: just reverse $row and 'field' order:
for ($row = 0; $row < count($date); $row++) {
$newArr[$row]['date'] = $date[$row];
$newArr[$row]['name'] = $name[$row];
...
}
First save the keys of your array - then by using array_value convert to integer keys so you can use the ... operator.
Then you can use array_filter with null function to re-organize your array. Next step will be to get the keys back using array_map and array_combine.
Last step - sort by "data" with usort
Consider the following example:
$arr = ["date" => ["3", "7", "5"], "name" => ["aa", "bb", "cc"]]; // this can have a lot more sub-array inside
$keys = array_keys($arr); // extract the keys for later use
$res = array_map(null, ...array_values($arr)); // transposed the array
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // return the keys to the transposed array
usort($res, function ($a, $b) {return strcmp($a['date'], $b['date']);} ); // sort all by "date"
Reference:
array-keys, array-filter, array-map, usort, array-values
Notice #MarcoS post comment regarding the comparing dates

Most efficient way to sort a multidimensional array (php)

I am looking for the most efficient way to sort a multidimensional array in php.I want to sort the array by the value name in [result][index][kl][0]. What is the fastest way to do this? My array has like 100 elements.
My array looks like this:
Array
(
[jsonrpc] => 2.0
[id] => req-002
[result] => Array
(
[0] => Array
(
[type] => subst
[lsid] => 11
[date] => 20150209
[startTime] => 955
[endTime] => 1040
[kl] => Array
(
[0] => Array
(
[id] => 29
[name] => S12UB
)
)
)
[1] => Array
(
[type] => subst
[lsid] => 11
[date] => 20150209
[startTime] => 1045
[endTime] => 1130
[kl] => Array
(
[0] => Array
(
[id] => 29
[name] => S12UB
)
)
)
Thank you.
Use a user-defined sort function, like usort along with strcmp:
function compareByName($a, $b) {
// the strcmp returns a numeric value above or below 0 depending on the comparison
return strcmp($a['k1'][0]['name'], $b['k1'][0]['name']);
}
Then, assuming your multi-dimensional array is named $array, replace the multi-dimensional array $array['result'] with the newly sorted array:
$array['result'] = usort($array['result'], 'compareByName');
The documentation for the usort and strcmp should be self-explanatory for understanding how the code works above.
$result = uasort($result, function($a, $b) {
return strcmp($a['kl'][0]['name'], $b['kl'][0]['name']);
});

Rewriting usort function because of fatal error (PHP bug)

The two following usort functions throw fatal error Base lambda function for closure not found in our productive environment (PHP 5.4). This seems to be a known PHP bug that should be fixed by now (https://bugs.php.net/bug.php?id=52144), but it still occurs for us.
Anyway, we unfortunately don't have time to figure out what's wrong with our PHP configurations etc. We would like to rewrite these two functions without the use of anonymous functions, so that the error doesn't occur anymore.
1) Ordering of a multidimensional array ($array) by value of key "position":
// ARRAY BEFORE
Array
(
[0] => Array
(
[ftid] => 3339685
[position] => 2
[auswahl] => 7179726
[keine_antwort] =>
)
[1] => Array
(
[ftid] => 3339686
[position] => 1
[auswahl] => 7179727
[keine_antwort] =>
)
)
// FUNCTION THAT NEEDS TO BE REWRITTEN
usort($array, function($a, $b) {
return $a['position'] - $b['position'];
});
// ARRAY AFTER
Array
(
[0] => Array
(
[ftid] => 3339686
[position] => 1
[auswahl] => 7179727
[keine_antwort] =>
)
[1] => Array
(
[ftid] => 3339685
[position] => 2
[auswahl] => 7179726
[keine_antwort] =>
)
)
2) Ordering of a multidimensional array ($array) according to the order of a second array ($position_order):
// $array before
Array
(
[0] => Array
(
[ftid] => 3339685
[position] => 1
[auswahl] => 7179726
[keine_antwort] =>
)
[1] => Array
(
[ftid] => 3339686
[position] => 2
[auswahl] => 7179727
[keine_antwort] =>
)
)
// $position_order (key value corresponds to key 'ftid' in $array
Array
(
[3339686] => 1
[3339685] => 2
)
// FUNCTION THAT NEEDS TO BE REWRITTEN
usort($array, function($a, $b) use($position_order) {
return (isset($position_order[$a['ftid']]) ? ($position_order[$a['ftid']] - $position_order[$b['ftid']]) : 1);
});
// $array
Array
(
[0] => Array
(
[ftid] => 3339686
[position] => 2
[auswahl] => 7179727
[keine_antwort] =>
)
[1] => Array
(
[ftid] => 3339685
[position] => 1
[auswahl] => 7179726
[keine_antwort] =>
)
)
Especially the latter causes some headache, as we don't know how to pass the "outside" array $position_order.
Someone may come up with a better usort implementation, but at least for the first one, this is how I do it:
function array_column_sort(&$array, $column, $sort=SORT_ASC) {
foreach($array as $key => $val) {
$sort_array[$key] = $val[$column];
}
array_multisort($sort_array, $sort, $array);
}
Works for the second (may want better func names):
function array_column_sort_array(&$array, $column, $sort_array) {
foreach($array as $val) {
$result[$sort_array[$val[$column]]] = $val;
}
ksort($result);
$array = array_values($result);
}

Sort Multi-dimensional array by value dynamically with PHP

This Stackoverflow answer is 95% of the way there: https://stackoverflow.com/a/10484863. I just need to pass another variable into the function which I believe uses closure.
I want to pass the variable sort:
$sort = get_category_name();
into:
function compareByName($a, $b) {
return strcmp($a["name"], $b["name"]);
}
usort($a, 'compareByName');
so its $a[$sort] and not defined by me as $a[key].
My array:
Array(
[0] => Array
(
[id] => 7
[product_type_id] => 2
[category_en] => Prints
[category_es] => Impresiones
[category_ru] => Печати
)
[1] => Array
(
[id] => 8
[product_type_id] => 2
[category_en] => Drawings
[category_es] => Dibujos
[category_ru] => Рисунки
)
[2] => Array
(
[id] => 9
[product_type_id] => 2
[category_en] => Paintings
[category_es] => Pinturas/Cuadros
[category_ru] => Картины
)
)
should allow me to sort the array by the category based on the users language which is set by get_category_name().

Php array sort by date after merge

Hi i have an array which is combinations of 2 separate array producing same result, following are my array after merge :
Array
(
[0] => Array
(
[event_id] => 16
[user_id] => 3
[date_created] => 20130227095010
)
[1] => Array
(
[event_id] => 15
[user_id] => 2
[date_created] => 20130227101734
)
[2] => Array
(
[event_id] => 16
[user_id] => 2
[date_created] => 20130227094856
)
)
From here onwards how can i sort again based on date_created desc or asc without using previously 2 arrays which i used to merge?
Update:
previous array result
array1:
Array
(
[0] => Array
(
[event_id] => 15
[user_id] => 2
[date_created] => 20130227101734
)
[1] => Array
(
[event_id] => 16
[user_id] => 2
[date_created] => 20130227094856
)
)
array 2:
Array
(
[0] => Array
(
[event_id] => 16
[user_id] => 3
[date_created] => 20130227095010
)
)
How can i use loop within these function to extract date_created for each of above arrays
usort($array,function($a, $b) { return $a['date_created'] - $b['date_created']; });
Very easy with something like usort().
usort($array,
function($a, $b) { return $a['date_created'] - $b['date_created']; });
You can create your own sort function callback and use it with the usort method.
There is need to re-use your first 2 arrays.
usort($yourMergedArray, yourCallBackSort);
and
function yourCallBackSort($firstEntry, $secondEntry)
{
// Do some stuff to compare your values and return -1, 0 or 1
// depend if $firstEntry id <, = or > to $secondEntry
}
Try this,
$sort = array();
foreach($your_combined_array as $k=>$v) {
$sort['date_created'][$k] = $v['date_created'];
}
array_multisort($sort['date_created'], SORT_DESC, $your_combined_array);
echo "<pre>";
print_r($your_combined_array);

Categories