Sort array by keys of another array - php

There are 2 arrays, both with the same length and with the same keys:
$a1 = [1=>2000,65=>1354,103=>1787];
$a2 = [1=>'hello',65=>'hi',103=>'goodevening'];
asort($a1);
The keys of a1 and a2 are id's from a database.
a1 gets sorted by value. Once sorted, how can we use the same sorting order in a2?
Thanks!

I believe this works:
$a1 = array(1=>2000,65=>1354,103=>1787);
$a2 = array(1=>'hello',65=>'hi',103=>'goodevening');
asort($a1); // sort $a1, maintaining array index
// sort $a2 by key, using the order of $a1
function my_uksort($a, $b) {
global $a1;
return $a1[$a] < $a1[$b] ? -1 : 1;
}
uksort($a2, 'my_uksort');
var_dump($a1);
var_dump($a2);

Not optimal maybe.. but it's short:
$a1 = array(1=>2000,65=>1354,103=>1787);
$a2 = array(1=>'hello',65=>'hi',103=>'goodevening');
asort($a1);
foreach(array_keys($a1) as $i) $out[$i] = $a2[$i];
echo join("\n", $out);
look into uasort() also

foreach($a1 as $key => $value){
//do something with $a2
echo $a2[$key];
}

You probably want to look at array_multisort() if you can handle losing ID association (arrays will be re-indexed).
array_multisort($a1, $a2);

Related

Merge the values of two or more arrays in php

Someone could be so nice to tell me how to do the following with 2 ore more arrays in PHP:
array 1 (a,b,c,d)
array 2 (1,2,3,4)
I would like to merge the two arrays in an unique array with the merged values:
Result: unique array (a-1,b-2,c-3,d-4).
Is there any function that does so? I could not find anything in the forum either on the web.
Thanks for all your answers but I guess that my arrays are a bit more structured because I need the final result for a dropdown field.
Now I have these 2 arrays:
$array1[] = array( 'text' => $hospital['value'], 'value' => $hospital['value'] );
$array2[] = array( 'text' => $company['value'], 'value' => $company['value'] );
I want to have a final array that contains: Hospital1 - Company1, Hospital2 - Company2, Hospital3 - Company3, etc..
Thanks
You can use array_map:
$result = array_map(function ($item1, $item2) {
return "$item1-$item2";
}, $array1, $array2);
Here is working demo.
You would have to create a loop to do this manually. it might look something like the following:
$a = array(a,b,c,d);
$b = array(1,2,3,4);
$c = array(); //result set
if(count($a) == count($b)){ // make sure they are the same length
for($i = 0; $i < count($a); $i++){
$c[] = $a[$i]."-".$b[$i];
}
}
print_r($c);
If i understand right, you can use array_combine where array 1 will be the key and array 2 the value.
Example usage:
$a = array(1,2,3,4);
$b = array(a,b,c,d);
$c = array_combine($a, $b);
var_dump($c);

Sorting array only using first element of an array in php

I have three arrays like this:
$a1 = array('55','something1','something2','something3' );
$a2 = array('77','something14','something25','something36' );
$a4 = array('66.6','something15','something25','something34' );
and a array of these three like this:
$a = array($a1,$a2,$a4 );
I know by using sort() I can sort numeric values but here what I want to sort above arraysin such a manner that sorting occurs only through first numeric element of arrays $a1,$a2 and $a4 i.e. output should be first $a1 because 55 less than 66.6 and 77 then $a4 because 66.6 is less than 77 and the $a2.I dont't want values of elements in arrays $a1 ,$a2,$a4 get changed only array $a should be rearranged nummerically.
using usort
usort — Sort an array by values using a user-defined comparison
function
$a1 = array('55','something1','something2','something3' );
$a2 = array('77','something14','something25','something36' );
$a4 = array('66.6','something15','something25','something34' );
$array = [$a1, $a2, $a4];
usort($array, function($a, $b) {
if ($a[0] > $b[0]) {
return 1;
} else {
return -1;
}
});
print_r($array);
live example: https://3v4l.org/QnUXc

Subtracting arrays to get every difference

What I have
$array1 = [1,1,1];
$array2 = [1,1];
What I'm doing:
array_diff( $array1, $array2 );
What I expected:
array(1) { 1 }
What I got
array(0) { }
How do I subtract two arrays to get every discrepancy?
Edit:
My example was incomplete, sorry.
If we also have values like this:
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
I would expect
[1,1,2,1] - [1,1,1,2] = []
array_diff_assoc() is the right way to go here. But to get your expected result you just have to sort the array first with usort() where I compare the values with strcasecmp().
So this should work for you:
<?php
$array1 = [1,1,2,1];
$array2 = [1,1,1,2];
function caseCmpSort($a, $b){
return strcasecmp($a, $b);
}
usort($array1, "caseCmpSort");
usort($array2, "caseCmpSort");
$result = array_diff_assoc($array1, $array2);
print_r($result);
?>
output:
Array ( )
use array_diff_assoc
$array1 = [1,1,1];
$array2 = [1,1];
print_r(array_diff_assoc( $array1, $array2)); // outputs Array ([2] => 1)
try it here http://sandbox.onlinephpfunctions.com/code/43394cc048f8c9660219e4fa30386b53ce4adedb
So you should check array key differences too. Have you tried array_diff_assoc()?
http://php.net/manual/en/function.array-diff-assoc.php
From manual:
Returns an array containing all the entries from array1 that are not present in any of the other arrays.
So, it is working as expected. I am not sure what exactly You want to achieve. You cloud try, it should give You expected result in this example.
$a = [1,1,1];
$b = [1,1];
print_r(array_diff_assoc($a,$b));
Edit: Well, simple sort should solve issue from Your comment. Nothe, that this will remove information of original indexes of elements.
$a = [1,1,2,1];
$b = [1,1,1,2,1];
sort($a);
sort($b);
print_r(array_diff_assoc($a,$b));
<?php
$n = array(1,1,1);
$m = array(1,1);
$r = array_diff_assoc($n,$m);
var_dump($r);
?>

How to increase by 1 all keys in an array?

What is the simplest solution to increase by 1 all keys in an array?
BEFORE:
$arr[0] = 'a';
$arr[1] = 'b';
$arr[2] = 'c';
AFTER:
$arr[1] = 'a';
$arr[2] = 'b';
$arr[3] = 'c';
You can use
$start_zero = array_values($array); /* Re-Indexing Array To Start From Zero */
And if you want to start it from index 1 use
$start_one = array_combine(range(1, count($array)), array_values($array));
Well, there's one very simple way to do it:
$arr = array('a', 'b', 'c');
array_unshift($arr, null);
unset($arr[0]);
print_r($arr);
/*
Array
(
[1] => a
[2] => b
[3] => c
)
*/
Will work only for simple dense arrays, of course.
And this is most untrivial (yet both a one-liner AND working for both dense and sparse arrays) way:
$arr = array_flip(array_map(function($el){ return $el + 1; }, array_flip($arr)));
I'm not sure why you'd want to do this, but you should just be able to loop through:
$new_array = array();
foreach($arr as $key => $value){
$new_array[$key+1] = $value;
}
$arr = $new_array;
$count = count($arr);
for($i=$count; $i>0; $i--){
$arr[$i] = $arr[$i-1];
}
unset($arr[0]);
I know this question is quite old, but I ran into a similar issue recently and came up with a nice one-liner to solve it for any type of array using an arbitrary integer as the starting key:
$array = array_combine(array_keys(array_fill($starting_index, count($array), 0)), array_values($array));
$starting_index is whatever value you want for the initial integer key, e.g. 3.
This can even be used with arrays holding complex objects, unlike the solution using array_flip and does not limit you to starting the index at 0 or 1 like some of the other solutions.
I'm not sure if this qualifies as a one liner but it is a different way of doing it
$result = array_reduce(array_keys($arr),function($carry,$key) use($arr){
$carry[$key+1] = $arr[$key];
return $carry;
},[]);

Is there a built-in sortByKey() function in PHP?

Say,$arr contains multiple sub-arrays with the key "pos",
$arr = sortByKey($arr,'pos');
After that the sub-array with smallest "pos" value will be ordered first,and so on.
EDIT
$sub1 = array('pos' => 2);
$sub2 = array('pos' => 1);
$arr = array($sub1,$sub2);
$arr = sortByKey($arr,'pos');
After this function,$arr will be array($sub2,$sub1)
see the ksort function.
here come the manual of the function.
sorry also I think you are ccase you are more looking into uasort you would be able to define a function to compare each of your elements and sort them
// Array to be sorted
print_r($array);
// Sort and print the resulting array
uasort($array, create_function('$a,$b', 'return $a[\'pos\'] == $b[\'pos\'] ? 0 : (($a[\'pos\'] < $b[\'pos\']) ? -1 : 1);'));
print_r($array);
have to be tested not sure about the double ? operator ...
Cheer
Let me write you a function. Its not tested.
function subarray_sort($array, $subkey) {
$sortarray=array();
foreach($array as $item) {
$sortarray[]=$item[$subkey];
}
array_multisort($sortarray, $array);
}

Categories