How to add 2 arrays and sort it - php

How can I turn:
$array1 = array(34=>"key1",54=>"key3",12=>"key2");
$array2 = array(44=>"key4",12=>"key2",1=>"key1");
into:
$array = ("key3"=>54,"key4"=>44,"key1"=>35,"key2"=>24);
How to add the value of the keys and sort by value?

You could flip the arrays, merge and sum matching key values, followed by a reverse sort:
$a1 = array(34=>"key1",54=>"key3",12=>"key2");
$a2 = array(44=>"key4",12=>"key2",1=>"key1");
function addRev($a1,$a2) {
$a1 = array_flip($a1);
$a2 = array_flip($a2);
$added = array();
foreach (array_keys($a1 + $a2) as $key) {
$added[$key] = #($a1[$key] + $a2[$key]);
}
arsort($added);
return $added;
}
print_r(addRev($a1, $a2));
Result:
Array
(
[key3] => 54
[key4] => 44
[key1] => 35
[key2] => 24
)

try this, I add explanations in comments
$array1 = array(34=>"key1",54=>"key3",12=>"key2");
$array2 = array(44=>"key4",12=>"key2",1=>"key1");
// fliping arrays
$a1r = array_flip($array1);
$a2r = array_flip($array2);
var_dump($a1r);
var_dump($a2r);
// adding the 2 arrays, final result in $a1r
foreach ($a2r as $key => $value) {
if (!isset($a1r[$key])) {
$a1r[$key] = 0;
}
$a1r[$key] += $value;
}
var_dump($a1r);

You can use array_merge() function for "adding" arrays.
http://php.net/manual/en/function.array-merge.php
For sorting, you can check this link:
Sorting an associative array in PHP

Related

How to return the array when it's similar

I has two array look like this.
array1 = [ array("A"=> array("0"=>"1",
"1"=>"2",
"2"=>"3"),
"B"=>"1"),
array("A"=> array("0"=>"1",
"1"=>"2"),
"B"=>"2")
];
$array2 = array("A"=> array("0"=>"1",
"1"=>"2"),
"B"=>"2",
"C"=>"POP",
"D"=>null);
Now i try to compare $array1 and $array2.
you will see $array2 is same with $array1 in "A" and "B"
This is my result i hope it's to be
$result = array("A"=> array("0"=>"1",
"1"=>"2"),
"B"=>"2");
And last i use php(laravel)
I try to use
array_intersect_assoc($array1, $array2);
but it gave a nothing
Why don't you define your own array_intersect_assoc as this:
function array_intersect_assoc_with_arrays($arr1, $arr2) {
$ret = [];
$commonkeys = array_intersect(array_keys($arr1), array_keys($arr2)); // get all the keys that appear in both array
foreach ($commonkeys as $key) {
if (json_encode($arr1[$key]) == json_encode($arr2[$key])) //convert inner array to string so we can compare them
$ret[$key] = $arr1[$key]; // if equal - set them in the response
}
return $ret;
}
Now you can use it with:
$array1 = [array("A"=> array("0"=>"1", "1"=>"2", "2"=>"3"), "B"=>"1"), array("A"=> array("0"=>"1", "1"=>"2"), "B"=>"2")];
$array2 = array("A"=> array("0"=>"1", "1"=>"2"), "B"=>"2", "C"=>"POP", "D"=>null);
$res= [];
foreach($array1 as $arr) { // for each sub-array get all the familiar fields
$res = array_merge(array_intersect_assoc_with_arrays($arr, $array2), $res);
}
Which will generate the following output:
Array
(
[A] => Array
(
[0] => 1
[1] => 2
)
[B] => 2
)
Hope that helps!

Assign key to array values

i have a function that i got from stack-overflow:-
function testFunction($a, $b) {
$map = array();
foreach($a as $name => $value){
if(!isset($b[$name]) || $b[$name] != $value) {
$map[$value] = 1;
}
}
return array_keys($map);
}
$array1 = array("Peter"=>"35", "Ben"=>"21", "Joe"=>"43");
$array2 = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"57");
print_r(testFunction($array2, $array1));
here is the result i get:
Array ( [0] => 37 [1] => 57 )
because the 37 in second array is different than 21 in first array... and the 57 is different than the 43.
my question is: how can i add a key to the values? for example, I want this:
Array ("Ben"=>"37", "Joe"=>"57");
You can do it like below:-
<?php
function testFunction($a, $b) {
$map = array();
foreach($a as $name => $value){
if(!isset($b[$name]) || $b[$name] != $value) {
$map[$name] = $value; // make key value array
}
}
return $map;
}
$array1 = array("Peter"=>"35", "Ben"=>"21", "Joe"=>"43");
$array2 = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"57");
print_r(testFunction($array2, $array1));
Output:- https://eval.in/735195
Short and optimized solution using array_intersect_key and array_diff functions:
$array1 = ["Peter"=>"35", "Ben"=>"21", "Joe"=>"43"];
$array2 = ["Peter"=>"35", "Ben"=>"37", "Joe"=>"57", 'I'=>0];
// getting all $array2 items with coincident keys
$common_key_items = array_intersect_key($array2, $array1);
// getting value difference between arrays with same keys
$result = array_diff($common_key_items, $array1);
print_r($result);
The output:
Array
(
[Ben] => 37
[Joe] => 57
)

Compare Associative arrays - return unmatched values

I have 2 associative arrays, like below.
Array
(
[Turbine] => 0
[Nuts and Bolts] => 6
[Runner Blade] => 5
)
Array
(
[Nuts and Bolts] => 10
[Runner Blade] => 5
[Turbine] => 1
)
What I want to do is compare the two arrays and return ones that have the same key but a different value. Similar to array_intersect_assoc, but that returns all values that match which is not what I want. Using the examples above what I want to return is the difference between the 2 values, something like:
Array
(
[Nuts and Bolts] => 4
[Turbine] => 1
)
Something like this:
$ar1;
$ar2;
foreach ($ar1 as $k => $v) {
if (intval($ar2[$k]) != intval($v))
$ar1[$k] = abs($v - $ar2[$k]);
else
unset($ar1[$k]); // remove key with equal value
}
Try this...
$newArr = array();
foreach($arr1 as $k=>$v){
$dif = abs($arr1[$k] - $arr2[$k]);
if($dif) $newArr[$k] = $dif;
}
print '<pre>';
print_r($newArr);
This will do what you want:
array_intersect_key($array1, $array2)
$diff = array_diff_assoc($arr1, $arr2);
$result = array();
foreach(array_keys($diff) as $key){
$result[$key] = abs($arr1[$key] - $arr2[$key]);
}
var_dump($result);

Add two arrays with the same length

I have two arrays,
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
what I want to achieve is to have a single array where the final form after adding the two arrays would be,
$arr_3 = array(01=>8, 02=>7, 03=>2);
I tried array_merge but it wasn't the solution.How would I attain the final form?
Try array_map. From the PHP Manual
array_map() returns an array containing all the elements of arr1
after applying the callback function to each one. The number of
parameters that the callback function accepts should match the number
of arrays passed to the array_map()
$arr_1 = array(01=>5, 02=>3, 03=>2);
$arr_2 = array(01=>3, 02=>4, 03=>0);
$arr_3 = array_map('add', $arr_1, $arr_2);
function add($ar1, $ar2){
return $ar1+$ar2;
}
print_r($arr_3);
OUTPUT:
Array ( [0] => 8 [1] => 7 [2] => 2 )
A for loop should handle this:
$max = count($arr_1);
$arr_3 = array();
for($i = 0; $i < $max; $i++){
$arr_3[$i] = intval($arr_1[$i]) + intval($arr_2[$i]);
}
I'm sure there are many other ways to do this, but this is the first one that came to mind. You could also do a foreach loop:
$arr_3 = array();
foreach($arr_1 as $k => $v){
$arr_3[$k] = intval($v) + intval($arr_2[$k]);
}
I'm just winging it here, the foreach is a little tricky to avoid the cartesian effects. Worth a shot though.
If you require adding elements matching by their key not by their position, you could try this:
$array1 = array(1=>5, 2=>3, 3=>2);
$array2 = array(3=>3, 2=>4, 1=>0); //unsorted array
$keys_matched = array_intersect_key ( $array1 , $array2);
foreach ($keys_matched as $key => $value) {
$result[$key] = $array1[$key] + $array2[$key];
}
print_r($result); //Displays: Array ( [1] => 5 [2] => 7 [3] => 5
You would look through both arrays and add each value of each array together then add that result to another array.
foreach($array1 as $val1) {
foreach($array2 as $val2) {
array_push($newArray, intval($val1)+ intval(val2));
}
}

Merge two sorted arrays and the resulting array should also be sorted

Let's say you have two arrays of arrays with the same structure but different count of arrays in them:
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
Now, the data in the $arr1 and $arr2 is sorted, and now what I would like it to merge these two arrays, so I did this:
$res = array_merge($arr1, $arr2);
And then I get an output like this:
1-b
2-a
5-c
3-e
But, I would like to have a sorted $res also like this:
1-b
2-a
3-e
5-c
I wonder if there's a function in PHP to do this automatically, without me having to write my own function? Or, please advise me on which is the best approach for this if I want to (later on) add sorting by the next parameter so the output would be like this
2-a
1-b
5-c
3-e
Thank you for all your help.
You can first merge the arrays and then sort the final array.
You are probably looking for a multi-sort function. I usually use this function (I found this functions somewhere on the internet years ago, credits go to the original author):
/*
* sort a multi demensional array on a column
*
* #param array $array array with hash array
* #param mixed $column key that you want to sort on
* #param enum $order asc or desc
*/
function array_qsort2 (&$array, $column=0, $order="ASC") {
$oper = ($order == "ASC")?">":"<";
if(!is_array($array)) return;
usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);"));
reset($array);
}
You can use it like this:
array_qsort2($res, 0, "ASC");
Why not simply call ksort($res) after your array_merge?
Since php v5.3 you can use anon functions in a more natural manner,
<?php
$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));
$arr2 = array(array(3,"e"));
$res = array_merge($arr1, $arr2);
usort($res, function($a,$b) {
// php7
// return $a[0] <=> $b[0];
if ($a[0] == $b[0]) return 0;
return $a[0] < $b[0] ? -1 : 1;
});
print_r($res);
output
Array
(
[0] => Array
(
[0] => 1
[1] => b
)
[1] => Array
(
[0] => 2
[1] => a
)
[2] => Array
(
[0] => 3
[1] => e
)
[3] => Array
(
[0] => 5
[1] => c
)
)
You can use below function to merge two sorted arrays without array_merge() or sort().
<?php
$arr1 = [1,2,5,7,10,20,36,70,82,90];
$arr2 = [4,6,10,15,65,85,90,100];
function shortt($array1,$array2){
$array1_count = count($array1);
$array2_count = count($array2);
while ($array1_count || $array2_count)
{
$array1_empty = $array1 == [];
$array2_empty = $array2 == [];
if (!$array1_empty && !$array2_empty)
{
if (current($array1) < current($array2))
{
$array3[] = array_shift($array1);
$array1_count--;
}
else
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
elseif (!$array1_empty)
{
$array3[] = array_shift($array1);
$array1_count--;
}
elseif (!$array2_empty)
{
$array3[] = array_shift($array2);
$array2_count--;
}
}
return $array3;
}
$newarr = shortt($arr1,$arr2);
print_r($newarr);
?>

Categories