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..
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 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.
I am trying to compare two different arrays and get the values that do not exist in 1 of the arrays. Here are my 2 arrays:
Array ( [0] => 2fbd5868-28ec-418d-854a-0736db720c8a [1] => f4a41974-5373-4862-a5e7-9d28b8c2301f [2] => a1874f68-3da1-47c3-97ef-a68580ce2a52)
Array ( [0] => 2fbd5868-28ec-418d-854a-0736db720c8a [1] => f4a41974-5373-4862-a5e7-9d28b8c2301f [2] => a1874f68-3da1-47c3-97ef-a68580ce2a52 [3] => 583cee91-1913-4e9d-b51d-e27083420001)
As you can see the second array has an additional value. I am trying to user array_diff like this:
$result = array_diff($array1,$array2);
print_r($result);
However the out of the array_diff is:
array()
Any ideas what is going on?
As people have suggested and i have already tested switching the arrays around, this is the output:
Array ( [0] => [1] => )
array_diff gives you the values from $array1 that are not in the other arrays. All the values of your first array are in the second. Sou change the order of your arrays and you should be fine.
See also here: http://php.net/manual/de/function.array-diff.php
The order of arguments in array_diff() is important
Returns an array containing all the entries from array1 that are not
present in any of the other arrays2
Read array_diff
$result = array_diff($array2,$array1);
Try like this
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.
Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)