I am trying to add 1st array value to 2nd array based on key match but not success with array_merge function see example of what i doing below
Array1
(
[99] => 99
[98] => 98
)
Array2
(
[99] => Array
(
[0] => 1300
[1] => 1500
[2] => 1618
[3] => 2704
[4] => 1401
[5] => 1900
[6] => 1100
[7] => 4232
[8] => 4233
)
[98] => Array
(
[0] => 1400
[1] => 4802
[2] => 1601
[3] => 1603
[4] => 1100
[5] => 1900
)
)
my code so far returning me wrong output like this
$finalArray = array_merge($Array1, $Array2);
what i am expecting
finalArray
(
[99] => Array
(
[0] => 1300
[1] => 1500
[2] => 1618
[3] => 2704
[4] => 1401
[5] => 1900
[6] => 1100
[7] => 4232
[8] => 4233
[9] => 99
)
[98] => Array
(
[0] => 1400
[1] => 4802
[2] => 1601
[3] => 1603
[4] => 1100
[5] => 1900
[6] => 98
)
)
i have tried array_merge, array_push & array combine as well but not success
please somebody help me on this
My Answer:
"apple",
[100] = "banana",
[101] = "orange"
)_Array2_(_ [99] = 5,
[100] = 10,
[101] = 15
)_Expected Output_(_ [99] = "apple5",
[100] = "banana10",
[101] = "orange15"
)_
You can achieve this by iterating over the arrays and combining the values based on the keys. Here's an example code snippet to achieve this:
php
$array1 = [
99 => "apple",
100 => "banana",
101 => "orange"
];
$array2 = [
99 => 5,
100 => 10,
101 => 15
];
$result = [];
foreach ($array1 as $key => $value) {
if (isset($array2[$key])) {
$result[$key] = $value . $array2[$key];
}
}
print_r($result);
This code will output:
Array
(
[99] => apple5
[100] => banana10
[101] => orange15
)
This code iterates over the keys in the first array and checks if the key exists in the second array. If it does, it combines the values and stores them in the result array.
Rate this post
4 of 5 based on 5702 votesComments