sorting array based on child array[0] (unix) value - php

I need an array sorted by Unix timestamp values. I attempted to use both ksort and krsort before realising that occasionally the timestamp values might be the same (and you cannot have duplicate keys in arrays).
Here's an example array I may be faced with:
$array = array(
[
"unix" => 1556547761, // notice the two duplicate unix values
"random" => 4
],
[
"unix" => 1556547761,
"random" => 2
],
[
"unix" => 1556547769,
"random" => 5
],
[
"unix" => 1556547765, // this should be in the 3rd position
"random" => 9
]
);
So what I'm trying to do is sort them all based on each child arrays unix value, however I cannot figure out how to do so. I have tried countless insane ways (including all other sort functions and many, many for loops) to figure it out - but to no avail.
All help is appreciated.

You can use usort which sort your array by given function
Define function as:
function cmpByUnix($a, $b) {
return $a["unix"] - $b["unix"];
}
And use with: usort($array, "cmpByUnix");
Live example: 3v4l
Notice you can also use asort($array); but this will compare also the "random" field and keep the key - if this what you need then look at Mangesh answer

array_multisort() — Sort multiple or multi-dimensional arrays
array_columns() — Return the values from a single column in the input array
You can use array_multisort() and array_column(), then provide your desired sort order (SORT_ASC or SORT_DESC).
array_multisort(array_column($array, "unix"), SORT_ASC, $array);
Explanation:
In array_multisort(), arrays are sorted by the first array given. You can see we are using array_column($array, "unix"), which means that the second parameter is the order of sorting (ascending or descending) and the third parameter is the original array.
This is the result of array_column($array, "unix"):
Array(
[0] => 1556547761
[1] => 1556547761
[2] => 1556547765
[3] => 1556547769
)

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
Note:If two members compare as equal, their relative order in the sorted array is undefined.
Refer : https://www.php.net/manual/en/function.asort.php
asort($array);
echo "<pre>";
print_r($array);
echo "</pre>";
It will give you the output as
Array
(
[1] => Array
(
[unix] => 1556547761
[random] => 2
)
[0] => Array
(
[unix] => 1556547761
[random] => 4
)
[3] => Array
(
[unix] => 1556547765
[random] => 9
)
[2] => Array
(
[unix] => 1556547769
[random] => 5
)
)
You can keep the array key [1],[0],[3],[2]) as it is Or you can keep it as sequential as per your requirement.

Related

Get values of array using as key values of another array

I have an array with some values (numeric values):
$arr1 = [1, 3, 8, 12, 23]
and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.
$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]
I want as return the values of $arr2 specifying as key the values of $arr1:
["foo", "foo20", "foo02", "foo39", "foo91"]
If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.
Minimal loop is simple - 1. as:
foreach($arr1 as $k) {
$res[] = $arr2[$k];
}
You can do that with array_walk but I think this simple way is more readable.
If you insist you can do with array_filter + array_values + in_array as:
$res = array_values(array_filter($arr2,
function ($key) use ($arr1) { return in_array($key, $arr1);},
ARRAY_FILTER_USE_KEY
));
You can see this for more about filtering keys
To do it purely with array functions, you could do it as...
print_r(array_intersect_key($arr2, array_flip($arr1) ));
So array_flip() turns the items you want form the array into the keys for $arr1 and then uses array_intersect_key() to match the keys with the main array and this newly created array.
Gives...
Array
(
[1] => foo
[3] => foo20
[8] => foo02
[12] => foo39
[23] => foo91
)
If you don't want the keys - add array_values() around the rest of the calls...
print_r(array_values(array_intersect_key($arr2, array_flip($arr1) )));
to get
Array
(
[0] => foo
[1] => foo20
[2] => foo02
[3] => foo39
[4] => foo91
)
Although as pointed out - sometimes a simple foreach() is just as good and sometimes better.

How to sort an array keys according to another array values with PHP

I have a problem in php array. Seems like it won't be very difficult who
have knowledge on array.
I have two arrays
Example:
1st array is:
Array (
[651] => 12
[620] => 10
[681] => 7
[792] => 6
[402] => 5)
1st array is sorted according to the values with descending order.
2nd array is:
Array (
[681] => Blue
[620] => White
[792] => Red
[651] => Green
[402] => Gray)
Both array has similar keys.
Now i want an array that should look like this
Array (
[651] => Green
[620] => White
[681] => Blue
[792] => Red
[402] => Gray)
That means 2nd array keys should be sorted according to the value of the 1st array.
Thank you very much.
You can use array_multisort. But you shouldn't sort the first array beforehand. If the first array sorted separately you should sync it back by sorting it by keys again (using ksort):
// Sync two arrays -- sort by keys.
ksort($array1);
ksort($array2);
// Sort second array accordingly to the first.
array_multisort($array1, SORT_DESC, $array2);
Here is working demo.
Pay attention that, with this approach, both arrays will be sorted in the end, but you will loose the keys, i.e. arrays will be reindexed.

Is there any function where I can sort array by value and if values are same it should print in the same order as they are supplied in the array?

I have currently looking for a function which sort the array in the following order:
for example:I have an array
$result=array("dddd"=>2,"ccc"=>4,"ddd"=>5,"pks"=>3,"sss"=>2,"test"=>2);
it should gives this output.
Array
(
[ddd] => 5
[ccc] => 4
[pks] => 3
[dddd] => 2
[sss] => 2
[test] => 2
)
I have tried arsort but it does not give the required output.any help will be appreciated.
You mean that you want the result sorted by values in reverse order and for duplicate values with the keys sorted in ascending order? Try this:
$result=array("dddd"=>2,"ccc"=>4,"ddd"=>5,"pks"=>3,"sss"=>2,"test"=>2);
array_multisort(array_values($result), SORT_DESC, array_keys($result), SORT_ASC, $result);
Output
Array
(
[ddd] => 5
[ccc] => 4
[pks] => 3
[dddd] => 2
[sss] => 2
[test] => 2
)
Edit: while re-reading the title of your question, I realize that you perhaps don't want to sort duplicate values using their keys, but using the initial position in the original array. In that case your question is a probably a duplicate of: Sort an associative array by value in descending and preserve order when values are same
Try the asort function: http://php.net/manual/en/function.asort.php
It allows sorting associative array with value. It keeps the order of the keys

How to sort a PHP array and using the same index for each element?

I have this array:
numbers = array(
"1"=>2
"2"=>5
"3"=>1
"4"=>12
);
if I used sort(numbers) the array will become
numbers = array(
"1"=>1
"2"=>2
"3"=>5
"4"=>12
);
the indexes still in same places just sort the numbers
I want to move the indexes also like the following:
numbers = array(
"3"=>1
"1"=>2
"2"=>5
"4"=>12
);
You should make use of the asort in this context.
This function sorts an array such that array indices maintain their
correlation with the array elements they are associated with. This is
used mainly when sorting associative arrays where the actual element
order is significant.
<?php
$numbers = array(1=>2,2=>5,3=>1,4=>12);
asort($numbers);
print_r($numbers);
OUTPUT :
Array
(
[3] => 1
[1] => 2
[2] => 5
[4] => 12
)

PHP Aligning Array Key Values

I've Googled it for two days, and tried looking at the PHP manual, and I still can't remember that function that aligns the key values for PHP arrays.
All I'm looking for is the function that takes this:
Array
(
[0] => 1
[3] => 2
[4] => 3
[7] => 4
[9] => 5
)
And converts it into this:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
Basically, the array is first sorted by key (their values attached to them stay with them), then all the keys are set to all the counting numbers, consecutively, without skipping any number (0,1,2,3,4,5,6,7,8,9...). I saw it being used with ksort() a few months ago, and can't see to remember or find this elusive function.
Well, you see, this one is hard, because the general description on the PHP array functions page does not say that this function does what you're looking for.
But you can sort the array using ksort(), and then use this: array_values() . From the page from the PHP manual:
array_values() returns all the values from the input array and indexes numerically the array.
You can use array_merge:
$array = array_merge($array);
It will reindex values with numeric keys.
Update: Using array_values as proposed in #LostInTheCode's answer is probably more descriptive.
function array_reset_index_keys($array)
{
$return = array();foreach($array as $k => $v){$return[] = $v;}return $return;
}
And then use like a regular function, should re index the array
you can also use native functions such as array_values which returns the values of an array into a single dimension array, causing it to be re indexed .

Categories