I want to sort the following multidimensional array by several keywords - let me explain in a simple way.
this is how the parts in my multidimensional array look like
[template] => Array
(
[0] => Array
(
[KeyA] => 123
[KeyB] => ABC
[KeyC] => #FFFFF
[custom] => Array
(
[0] => Array
(
[value] => bla
[var] => 2
)
[1] => Array
(
[value] => c1
[var] => 5
)
)
)
)
there are tons of multidimensional arrays in that template array and I want them now to sort for example by KeyC (#00000 first prio, #FFFFFF second prio, #333333 third prio) and then by KeyA alphabetic.
How to do that ?
PHP has several functions that deal with sorting arrays and the logic behind array sorting are:
Some sort based on the array keys, whereas others by the values: $array['key'] = 'value';
Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...)
The order of the sort: alphabetical, low to high (ascending), high to low (descending), numerical, natural, random, or user defined
If any of these sort functions evaluates two members as equal then the order is undefined (the sorting is not stable).
Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array.
The main functions of sorting are described http://www.php.net/manual/en/array.sorting.php and for creating custom sorting you have to tricks best suitable to yourself.
Related
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.
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.
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
)
i have some problem to understand array_multisort
See how it sorts when two values are the same:
$a1=array("Dog","Dog","Cat");
$a2=array("Pluto","Fido","Missy");
array_multisort($a1,$a2);
print_r($a1);
print_r($a2);
The output of the code above will be:
Array ( [0] => Cat [1] => Dog [2] => Dog )
Array ( [0] => Missy [1] => Fido [2] => Pluto )
let me know why Missy comes first, if you do by ascending it must be
Array ( [0] => Fido, [1] => Missy, [2] => Pluto )
for descending vise versa
also see this
With sorting parameters:
$a1=array("Dog","Dog","Cat");
$a2=array("Pluto","Fido","Missy");
array_multisort($a1,SORT_ASC,$a2,SORT_DESC);
print_r($a1);
print_r($a2);
The output of the code above will be:
Array ( [0] => Cat [1] => Dog [2] => Dog )
Array ( [0] => Missy [1] => Pluto [2] => Fido )
but Array ( [0] => Missy [1] => Pluto [2] => Fido ) not at SORT_DESC is some type of mixed up.
can some one explain me how the array_multisort is working, so that i can understand how it's working.
Well, you're sorting the arrays in a similar way to programs like Excel. Each array corresponds to a column.
First, all arrays are sorted by the first array given. If there are identical values, those affected are sorted by the second array given. If there are again equal values, the third array is used, etc.
Or in other words: The arrays are sorted using all arrays, but beginning on the right (if you assume it really sorts by all columns once).
For your particular example (the second one):
At first you want to sort in ascending order, so Cat will be first. Therefore the last array element will be moved to the first position in both arrays. The other two elements, Dog are equal. This causes the function to look at the next array. It's told to sort this array in descending order, so Pluto comes first. In this case this leads to the result that the elements aren't moved at all (as their order is correct already).
The entries in the second array corresponding to the identical entries in the first array.
If you look at the documentation and the first example, you'll notice that this is the expected behavior.
With two arguments, both arrays: the first array is sorted; the second array will have its corresponding values re-arranged and sorted if the corresponding values in first column tie. As for your example, think of it as you're doing a SQL ORDER BY Animal, Name:
Cat comes first
The two Dogs have a tie so Fido comes first because Fido < Pluto
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 .