How can I compare two nested arrays in PHP? - php

Recently, I encountered some problem on comparing 2 nested arrays. I have tested to use array_diff_assoc to compare 2 arrays but it return me incorrect. Below are couple scenarios that I am attempt to compare these 2 nested array in php.
$arr1 = ["colorFamily"=>[]];
$arr2 = ["colorFamily"=>["blue","black"]];
$diff = array_diff_assoc($arr1,$arr2);
The $diff is expected to return below;
["colorFamily"=>[]]
Unfortunately, it return below:
[]
Aside from that, there are more complex scenario will be used in the comparison such as
$arr1 = ["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"],["value"=>"apple"]]];
$arr2 = ["colorFamily"=>["blue","black"],"descriptionMeasurement"=>[["label"=>"orange"]]];
Above scenario, it should return
["colorFamily"=>[],"descriptionMeasurement"=>[["label"=>"orange"]]].
In short, anything occurs in $arr1 and it is not occurs in $arr2, should return in the $diff array.
I hope you guys can help me to resolve this problem, I have been stucking for weeks.

With array_diff you should always put the array with the missing values first, otherwise it doesn't return anything.
Also it can't see past the first array. So something like this will work:
$diff = array_diff_assoc($arr2["colorFamily"], $arr1["colorFamily"])
You could also use the following. array_map is used to index the keys:
$missing = array_map('unserialize', array_diff(array_map('serialize', $arr2), array_map('serialize', $arr1)));
(credits: Use array_diff_assoc() or get difference of multidimensional arrays)

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

difference of two arrays in php, one with keys and another without

$a = array("a","b");
$b = array("a"=>"one", "b" => "two","c"=>"three");
I need help in finding the difference between two arrays one with key and another without key.
required output
"c"=>"three"
Use array_diff_key() and array_flip():
$difference = array_diff_key(
$b,
array_flip($a)
);
For reference, see:
http://php.net/manual/en/function.array-diff-key.php
http://php.net/manual/en/function.array-flip.php
For an example, see:
https://3v4l.org/YgNhB
Every array has keys. Even if you have not set them.
So, your arrays look like this:
$a = array(0=>"a",1=>"b");
$b = array("a"=>"one", "b" => "two","c"=>"three");
And you trying to compare the values of one array with the keys of the other.
That's why localheinz is using array_flip() in his answer.

PHP Merge two indexed arrays but NOT normally [duplicate]

This question already has answers here:
Merge two flat indexed arrays of equal size so that values are pushed into the result in an alternating fashion
(2 answers)
Closed last month.
I have two arrays:
$array1 = array("A","One","C","Z");
$array2 = array("B","K","2","5");
Is there some built-in PHP way to get a final array with (I don't know how to say it, maybe 1-1 correspondence addition) alternate keys appended to each other like this
$final_array = array("A","B","One","K","C","2","Z","5");
If I use array_merge, I get:
$final_array = array("A","One","C","Z","B","K","2","5")
But that's exactly what an array_merge does. Is there any workaround other than looping?
Try this:
$array1 = array(1,3,5,7);
$array2 = array(2,4,6,8);
$final_array = array_merge($array1,$array2);
sort($final_array);
print_r($final_array);
Hope this helps. Sorted the array using the sort function.

PHP : Getting not matched records from 2 arrays

Below are the 2 arrays
$full = array('ABCD19ed81424931667', 'ABCD0c08b1424947569');
$filtered = array('ABCD19ed81424931667');
I want the records which are not matching in 2 arrays. I have tried
array_diff, array_diff_assoc functions it did not work for me.
array_diff returns the difference in 1 direction. To get the difference in both directions you can do 2 array_diff followed by a array_merge:
$output = array_merge(array_diff($full, $filtered), array_diff($filtered, $full));
array_diff — Computes the difference of arrays.
Here array_diff(A,B) and array_diff(B,A) is different.
$full = array('ABCD19ed81424931667', 'ABCD0c08b1424947569');
$filtered = array('ABCD19ed81424931667');
$result = array_merge(array_diff($full, $filtered), array_diff($filtered, $full));
array_diff(A,B) returns all elements from A, which are not elements of B (= A without B). so you need to merge output

Opposite of array_intersect?

Is there a built-in function to get all members of array 1 which do not exist in array 2?
I know how to do it programatically, only wondering if there is a built-in function that does the same. So please, no code examples.
That sounds like a job for array_diff.
Returns an array containing all the
entries from array1 that are not
present in any of the other arrays.
array_diff is definitely the obvious choice but it is not technically the opposite of array interesect. Take this example:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
print_r( array_diff($arr1, $arr2) );
What you want is a result with 'rabbit' and 'bird' in it but what you get is only rabbit because it is looking for what is in the first array but not the second (and not vice versa). to truly get the result you want you must do something like this:
$arr1 = array('rabbit','cat','dog');
$arr2 = array('cat','dog','bird');
$diff1 = array_diff($arr1, $arr2);
$diff2 = array_diff($arr2, $arr1);
print_r( array_merge($diff1, $diff2) );
Note: This method will only work on arrays with numeric keys.
$diff = array_diff($array1, $array2);
array_diff()
Just to clarify as I was looking into this question the answers of #Jon and #Dallas Caley are both correct depending on the domain of your arrays.
If the array against what you are comparing is the full domain of your results then a simple array_diff will suffice as per #Jon answer.
If the array against what you are comparing is NOT the full domain of your results then you should go with the double array_diff as per #Dallas Caley answer.

Categories