Sorting two corresponding arrays in PHP - php

I have two arrays, both have numbers but are extracted in specific order from a database.
So what I want to do is to sort one of them in a acceding mode and the second array rearrange it's values to correspond the first one.
for instance
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
So in our example I need the first array to become (14,20,30) witch can be made with the sort function but the second also have to become (4,3,2) to correspond with the first array.
Any ideas?

You can use array_combine to make one array and then sort it

You need to use array_multisort:
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
array_multisort($firstarray, $secondarray);
var_dump($firstarray, $secondarray);
Online demo: http://ideone.com/FyU1cl

You can use array_combine to use the first array as keys and the second array as values.
$firstarray=array(14,30,20);
$secondarray=array(4,2,3);
$Array = array_combine($firstarray, $secondarray);
Output:
Array
(
[14] => 4
[30] => 2
[20] => 3
)
Then sort the keys asc.
ksort($Array);
Output:
Array
(
[14] => 4
[20] => 3
[30] => 2
)
And if you want to have a seperate $secondarray you can do:
$secondarray = array_values($Array);
$secondarray = array_flip($secondarray); // Values are keys now.

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.

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

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.

PHP - Why doesn't array_multisort function sort correctly?

please view the following code with 2 arrays. i use multisort function with sort flags for ascending and numeric then display. as you can see in the output that array 2 starts with 100 when it should be last. please explain what is causing this and how to sort it correctly. thank you.
<?php
$array1 = array(1,7,10,6);
$array2 = array(100,20,25,10);
array_multisort($array1, SORT_ASC, SORT_NUMERIC, $array2);
print_r($array1);
echo "<br>";
print_r($array2);
?>
output:
Array ( [0] => 1 [1] => 6 [2] => 7 [3] => 10 )
Array ( [0] => 100 [1] => 10 [2] => 20 [3] => 25 )
Ah, yes, array_multisort is a bit tricky to understand the first time round.
Basically the sort is lexicographical, a fancy word meaning that the first array is sorted and the second arrays elements are ordered according to the first array.
Look at your first (output) array and see the order and map it to the initial second array and you'll see whats happening.
So the second array you take the 1st, 4th , 2nd and 3rd elements.
If you just want plain sorting for multiple arrays then just do them one by one or over a loop.

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

get difference from three arrays by value

I am trying to get the difference between three arrays
array_diff() function doesn't help because it matches only the first array with others
For example I want to compare three arrays and each array has one of the element different from each other like this
$a1=array("a"=>"red","b"=>"green","c"=>"blue", 'v1' => 'sss');
$a2=array("e"=>"red","f"=>"green","g"=>"blue", 'v2' => 'ss');
$a3=array("e"=>"red","f"=>"green","g"=>"blue", 'v3' => 's');
when I use array_diff() on these arrays it would just show me the unique value out of other two arrays
$res = array_diff($a1, $a2, $a3);
print_r($res);
It's result would be Array ( [v1] => sss )
While I want it to tell me the unique values in all these arrays like this Array ( [v1] => sss [v2] => ss [v3] => s )
I tried other array comparison functions but couldn't find one to compare all given array to each other instead of comparing just one array to others
$var=(array_diff($a1,$a2,$a3));
$var1=(array_diff($a2,$a1,$a3));
$var2=(array_diff($a3,$a2,$a1));
$v=array_merge($var,$var1,$var2);
I guess this helps for you.check it out..

Categories