php - Combine two arrays by key
Get the solution ↓↓↓I have two arrays:
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value] => 60.00000
)
[15473] => Array
(
[id] => 15473
[group] => 9109
[value] => -15.000000
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value] => -20.000000
)
)
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value_prev] => 100.000000
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value_prev] => -100.000000
)
)
I'm trying to combine these arrays by the key and to add new element (value_prev) if match, or 0 if doesn't exist, so I need these arrays:
Array
(
[15407] => Array
(
[id] => 15407
[group] => 9083
[value] => 60.00000
[value_prev] => 100.000000
)
[15473] => Array
(
[id] => 15473
[group] => 9109
[value] => -15.000000
[value_prev] => 0
)
[15474] => Array
(
[id] => 15474
[group] => 9109
[value] => -20.000000
[value_prev] => -100.000000
)
)
I tried with array_keys function but couldn't get required array. There are some solution I have found but non helped me cause the structure of the arrays is not the same.
Answer
Solution:
Since the arrays are associative it's a very simple task.
Loop array one and see if the key exist in array 2, if it does copy value, else add 0 value.
$keys = array_keys($arr2);
foreach($arr1 as $key => &$sub){
if(in_array($key, $keys)){
$sub["value_prev"] = $arr2[$key]["value_prev"];
}else{
$sub["value_prev"] = 0;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to a member function format() on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.