Is there a quick way to combine one arrays values as the other array's keys?
Input:
array A => Array (
[0] => "cat"
[1] => "bat"
[2] => "hat"
[3] => "mat"
)
array B => Array (
[0] => "fur"
[1] => "ball"
[2] => "clothes"
[3] => "home"
)
Expected output:
array C => Array (
[cat] => "fur"
[bat] => "ball"
[hat] => "clothes"
[mat] => "home"
)
How could I do that?
In order to merge two arrays, we find its length and stored in fal and sal variable respectively. After that, we create a new integer array result which stores the sum of length of both arrays. Now, copy each elements of both arrays to the result array by using arraycopy() function.
You can use the numpy. concatenate() function to concat, merge, or join a sequence of two or multiple arrays into a single NumPy array. Concatenation refers to putting the contents of two or more arrays in a single array.
Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
To concate two arrays, we need at least three array variables. We shall take two arrays and then based on some constraint, will copy their content into one single array. Here in this example, we shall take two arrays one will hold even values and another will hold odd values and we shall concate to get one array.
array_combine()
will exactly do what you want.
Quoting the manual:
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.
In your case, you'd have to do something like this:
$array['C'] = array_combine($array['A'], $array['B']);
While of course you could also use various combinations of loops to do that, array_combine()
is probably the simplest solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With