I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.
Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines?
$mapped_array = mapkeys($array_with_keys, $array_with_values);
See array_combine() on PHP.net.
(from the docs for easy reading)
array_combine — Creates an array by using one array for keys and another for its values
Description
array array_combine ( array $keys , array $values )
Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values.
Parameters
keys - Array of keys to be used. Illegal values for key will be converted to string.
values - Array of values to be used
Example
<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
?>
The above example will output:
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
This should do the trick
function array_merge_keys($ray1, $ray2) {
$keys = array_merge(array_keys($ray1), array_keys($ray2));
$vals = array_merge($ray1, $ray2);
return array_combine($keys, $vals);
}
Related
I have this dynamic multiple arrays that I need to combine in one array and serialized them. The problem is I need to keep both key and value.
$arr = array($bet_option_id => $bet_option_name);
Here i need to keep both bet_option_id AND bet_option_name. Then this result output:
Array ( [997650802] => Over 2.5 )
Array ( [997650807] => Yes )
This need to be simply
Array
(
[997650802] => Over 2.5
[997650807] => Yes
)
As it's dynamic, sometimes not comes with just single array so apparently I couldn't get it working. I need to retrieve both bet_option_id & bet_option_name. Tried something like this:
$arr = array($bet_option_id => $bet_option_name); //This is where all array keys, values are stores
$result = array();
foreach ($arr as $array) {
$result = array_merge($result, $array);
}
Any inputs will be nice.
Rather than create individual arrays like...
$arr = array($bet_option_id => $bet_option_name);
If you first create an empty array ( like you do with $result)
$arr = array();
and then add each item in using
$arr[$bet_option_id] = $bet_option_name;
Then you don't need to manipulate the array after - just create it as you want it in the first place.
You could either do like Nigel Ren suggested which is the most elegant solution
In case that you do not have arrays that their keys are entirely numeric you may use array_merge. The quote following is from PHP array-merge
Example #2 Simple array_merge() example
$array1 = array();
$array2 = array(1 => "data");
$result = array_merge($array1, $array2);
Don't forget that numeric keys will be renumbered!
Array
(
[0] => data
)
Alternatively you can always join arrays together like this
$a1 = [ 997650802 => 'Over 2.5' ];
$a2 = [ 997650807 => 'Yes' ];
var_dump( $a1 + $a2 ); // result is [997650802 => 'Over 2.5',997650807 => 'Yes']
You can check more about Array Types and Array Operators
I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here
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 have two arrays
1st array
first array containts 60 strings like this:
['string1','string2', ... , string60];
2nd array
And I have an associative array like this:
['Key' => value, ..., 'Key' => value]
What I need to do is compare each value from first array(that contains 60 ellements), with each key from the second array, and if second(associative) array doesn't contain key that matches any value from first array - I should add such ellement to the associative array.
For example second array doesn't have key that matches string5 for example, and I'm not talking about value of the key, I'm literally talking about Key itself. So now I need to add string5 as a new key => value ellement to the array, the Key must be the word string5, and the value must be empty.
What is the best way to do it?
Not more complicated than:
$combined = $array2 + array_fill_keys($array1, null);
array_fill_keys creates an array like ['string1' => null, ..], + adds all of these keys which don't already exists in $array2.
$combined = $array2 + array_fill_keys($array1, null);// key value will be maintained
array_values($array2); //index starts from 0
This should work
foreach($array_1 as $val) {
if(!isset($array_2[$val])) {
$array_2[$val] = null;
}
}
pretty sure there are people who know more efficient ways (resource wise) as this might take long when you have huge arrays.
Here is the logical way to do this.
First divide the second array in key and values array. I mean two different array.
So
$keys = array_keys($array2);
$values = array_values($array2);
now you have to take the different from $array1 to $array2 sigular or vice-versa ( Depends on your requirement ) and it will give you the difference of missing keys.
$diff = array_diff($array1,$keys);
Now you will be able to find it easily.
Please refer to array_diff Source: php.net
<?php
$required = array('key1', 'key2', 'key3','key4');
$data = array(
'key1' => 10,
'key2' => 20
);
$arrayDiff = array_diff_key(array_flip($required),$data);
$final = array_merge($data,$arrayDiff);
// Result
// Array
//(
// [key1] => 10
// [key2] => 20
// [key3] => 2
// [key4] => 3
//)
?>
If you want default value to be populated to the new keys added to the array, add below line before merge and use the variable $arrayFill instead of $arrayDiff in the merge statement
$arrayFill = array_fill_keys(array_flip($arrayDiff),0);
I have an array of multidimentional arrays. Each array represents a result set from a search. I am having trying to figure out how to filter this set of data to only include arrays that are present in each array.
Note: The index's shown below each represent multidimentional arrays. Each array has a deeply nested Id key that can be used for comparison.
The Id is located at:
$reference_variable['data']['Id'][0]
For example,
array(
array([0], [19], [21], [148]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
Should return:
array(
[21]
)
and:
array(
array([0], [12], [15]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
Should return:
array(
[]
)
What is the best way to handle this? array_intersect does not work well with multidimensional arrays.
I've already tried storing all Ids in an array, and using array_count_values to find duplicate Ids, and then use array_filter to compare if the Id of the current array was equal to any of the duplicate Id's.
But that turned out to be totally wrong since this method would allow:
array(
array([0], [19], [21], [148]),
array([2], [21], [32], [44], [432], [549]),
array([13], [21], [148])
)
To return:
array(
[21, 148]
)
Which is not the intersection of all arrays.
Just store the indexes of the first array in an array. Check for matching indexes on the second array and store those in a second array A2. Check for matches between the second stored array ( A2 ) and the third array. Call it A3 for consistency ( A3 ). This is your answer.
Maybe 10-20 lines of code.
This was the answer in my case:
$params = array_merge($array_of_arrays, array('array_compare'));
$intersection = call_user_func_array('array_uintersect', $params);
function array_compare($a1, $a2)
{
if ($a1 === $a2) {
return 0;
}
if ($a1 > $a2) {
return 1;
}
return -1;
}
Credit: https://stackoverflow.com/a/2020654/1911755