Php array sort by date after merge - php

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);

Related

Find if two different keys have the same value in 2 arrays PHP

My arrays are:
Array1
(
[0] => Array
(
[id] => 2
[name] => Melamine
[deleted] => 0
)
[1] => Array
(
[id] => 4
[name] => Vinyl
[deleted] => 0
)
[2] => Array
(
[id] => 5
[name] => Polyu
[deleted] => 0
)
)
Array2
(
[0] => Array
(
[productFinish] => 29
[type] => 2
)
[1] => Array
(
[productFinish] => 29
[type] => 4
)
)
So, i would like to return first array if id of 1st array matches with type of another array. In this case, first 2 indexes of first array must come out in return.
Thanks
You can use array_uintersect to get the results you want, supplying a callback function that compares the id value in array1 with the type value in array2:
$result = array_uintersect($array1, $array2, function ($a1, $a2) {
return ($a1['id'] ?? $a1['type']) - ($a2['type'] ?? $a2['id']);
});
print_r($result);
Note that because the callback is also called with values exclusively from $array1 or $array2 (for sorting), we have to allow for that in the comparison expression.
Output:
Array
(
[0] => Array
(
[id] => 2
[name] => Melamine
[deleted] => 0
)
[1] => Array
(
[id] => 4
[name] => Vinyl
[deleted] => 0
)
)
Demo on 3v4l.org
Ok, i got it with for loop.
$newTypeFilter = [];
for($i=0; $i < count($arra1); $i++){
for($j=0;$j<count($arra2); $j++){
if($arra1[$i]['id'] == $arra2[$j]['type']){
$newTypeFilter[] = $arra1[$i];
}
}
}
Any other answers will be appreciated. Thanks

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

Sort Multidimensional array by two variables - 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;
}

PHP array sort using inner val

Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[3] => Array
(
[id] => 3
[sort] => 3
)
[2] => Array
(
[id] => 2
[sort] => 2
)
)
How do i sort it so its re-ordered using the inner 'sort' key ? ie the above would look like this:
Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[2] => Array
(
[id] => 2
[sort] => 2
)
[3] => Array
(
[id] => 3
[sort] => 3
)
)
You can use usort with this comparison function:
function cmpBySort($a, $b) {
return $a['sort'] - $b['sort'];
}
usort($arr, 'cmpBySort');
Or you use array_multisort with an additional array of key values for the sort order:
$keys = array_map(function($val) { return $val['sort']; }, $arr);
array_multisort($keys, $arr);
Here array_map with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.
Something like this:
usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });
Something like this:
uasort($array, 'compfunc');
function compfunc($a, $b)
{
return $a['sort'] - $b['sort'];
}

Sorting an array of an array of objects in PHP by key value

Basically I have a setup like the following:
Array (
[0] => Array ( [0] => stdClass Object ( [nid] => 1 [title] => title1 [uid] => 1 [parent] => 0 [weight] => -15 [name] => name1 [value] => 0 )
[1] => stdClass Object ( [nid] => 2 [title] => title2 [uid] => 1 [parent] => 0 [weight] => -7 [name] => name2 [value] => 100 )
[2] => stdClass Object ( [nid] => 3 [title] => title3 [uid] => 2 [parent] => 0 [weight] => -1 [name] => name3 [value] => 0 )
[3] => stdClass Object ( [nid] => 4 [title] => title4 [uid] => 2 [parent] => 0 [weight] => 1 [name] => name4 [value] => 80 )
)
)
What I need is a way to sort all the arrays inside the parent array by the [value] key in the Object. I've been trying for about 2 days now with usort and different methods but I just can't seem to get my head around it. The [value] key will range anywhere from 0 to 100 and I need all of the arrays sorted in decreasing order (IE: 100 down to 0).
Use usort:
function cmp($a, $b) {
if ($a->value == $b->value) {
return 0;
} else {
return $a->value < $b->value ? 1 : -1; // reverse order
}
}
usort($arr, 'cmp');
100% stolen from the 1st answer on this page.
http://us.php.net/manual/en/function.array-multisort.php
But this is what I was looking for.
multisort an Array of Objects:
example object [$object with array of objects]: (class: test)
----------------------------------
test Object (
[Artikel] => Array (
[0] => test Object (
[id] => 1
[title] => CCCC
)
[1] => test Object (
[id] => 2
[title] => AAAA
)
[2] => test Object (
[id] => 3
[title] => DDDD
)
[3] => test Object (
[id] => 4
[title] => BBBB
)
)
)
----------------------------------
Simple PHP function: sort_arr_of_obj()
<?php
// --------------------------------------
/*
* -------- function arguments --------
* $array ........ array of objects
* $sortby ....... the object-key to sort by
* $direction ... 'asc' = ascending
* --------
*/
function sort_arr_of_obj($array, $sortby, $direction='asc') {
$sortedArr = array();
$tmp_Array = array();
foreach($array as $k => $v) {
$tmp_Array[] = strtolower($v->$sortby);
}
if($direction=='asc'){
asort($tmp_Array);
}else{
arsort($tmp_Array);
}
foreach($tmp_Array as $k=>$tmp){
$sortedArr[] = $array[$k];
}
return $sortedArr;
}
// --------------------------------------
?>
example call:
----------------------------------
<?php
$sorted->Artikel = sort_arr_of_obj($object->Artikel,'title','asc');
?>
example result: $sorted (class: test)
----------------------------------
test Object (
[Artikel] => Array (
[0] => test Object (
[id] => 2
[title] => AAAA
)
[1] => test Object (
[id] => 4
[title] => BBBB
)
[2] => test Object (
[id] => 1
[title] => CCCC
)
[3] => test Object (
[id] => 3
[title] => DDDD
)
)
)
A way to do this is to separate the value array from the array of objects, and thus, creating two arrays. You can then use array_multisort to sort the array of objects according to the other array. Here's an example:
<?php
$array1 = $objectvalues
$array2 = array(ObjectWithNid1, ObjectWithNid2, ObjectWithNid3, ObjectWithNid4);
array_multisort($array1, $array2);
?>
You can use a foreach to loop the array one time and create a new array with the corresponding [value] key:
<?php
foreach( $arraywithobjects as $obj )
{
$objectvalues[] = $obj->getValue();
}
?>
This will get the Object's value and insert it into another array which you can use with the multisort.
In the end, your code will look like this:
<?php
foreach( $arraywithobjects as $obj )
{
$objectvalues[] = $obj->getValue();
}
$array2 = array(ObjectWithNid1, ObjectWithNid2, ObjectWithNid3, ObjectWithNid4);
array_multisort($objectvalues, $array2);
?>
The first array in the array_multisort field should be the array you're using to sort the second array.
You can also add other sorting method for this. You can read them here: link text
function cmp($a, $b) {
return $b->value - $a->value;
}
$ary[0] = usort($ary[0], "cmp");
In order to sort an array based on anything other than simple value or key, you need to use the usort function and supply your own comparison. Comparison functions must be defined such that if $a comes before $b, a positive value is returned and a negative one if $b comes before $a (or zero if they are equal). As you are comparing based on number values and you want a reverse sort, the simplest way of doing this is to subtract the 'value' of $a from the value of $b.
I could be wrong, but I believe I did something like this using asort() (or asort()). It was in a search function, where I needed to sort a two-dimensional array filled with indices and timestamps.
I'm not sure if it will work in your case, and I did it long ago. Maybe it will get you started though, good luck.

Categories