Way to compare array key & replace value if found (PHP)

Hello i am trying to make an php application, but i am having some trouble with arrays Actually, I m trying to compare array key & if found replace its value & merge whole array into one.
For example
Array ONE-
Array
(
[0] => Array
(
[label] => July 20 2020
[y] => 3
)
[1] => Array
(
[label] => July 18 2020
[y] => 1
)
)
Array TWO-
Array
(
[0] => Array
(
[label] => July 18 2020
[y] => 0
)
[1] => Array
(
[label] => July 19 2020
[y] => 0
)
[2] => Array
(
[label] => July 20 2020
[y] => 0
)
[3] => Array
(
[label] => July 21 2020
[y] => 0
)
)
To desired output array
Array
(
[0] => Array
(
[label] => July 18 2020
[y] => 1
)
[1] => Array
(
[label] => July 19 2020
[y] => 0
)
[2] => Array
(
[label] => July 20 2020
[y] => 3
)
[3] => Array
(
[label] => July 21 2020
[y] => 0
)
)
I have tried
array_merge($arrayone, $arraytwo)
;
but it doesn't work. Is it possible to get the desired output ?
This is how array looks like - https://imgur.com/a/HUQUmZz Please share your thoughts on this. Thankyou
Answer
Solution:
With your arrays, I do not think there is a smart way to do it, but this should work :
<?php
$datesArray = [
[
'label' => 'July 18 2020',
'y' => 0,
],
[
'label' => 'July 19 2020',
'y' => 0,
],
[
'label' => 'July 20 2020',
'y' => 0,
],
[
'label' => 'July 21 2020',
'y' => 0,
],
];
$valuesArray = [
[
'label' => 'July 20 2020',
'y' => 3,
],
[
'label' => 'July 18 2020',
'y' => 1,
],
];
foreach($datesArray as &$dateArray) {
foreach($valuesArray as $valueArray) {
// use ?? if php version allows it, else do isset($valueArray['label']) ? $valueArray['label'] : null;
$currentLabel = $valueArray['label'] ?? null;
if ($currentLabel === $dateArray['label']) {
$dateArray['y'] = $valueArray['y'] ?? 0;
}
}
}
print_r($datesArray);
return $datesArray;
Result :
Array
(
[0] => Array
(
[label] => July 18 2020
[y] => 1
)
[1] => Array
(
[label] => July 19 2020
[y] => 0
)
[2] => Array
(
[label] => July 20 2020
[y] => 3
)
[3] => Array
(
[label] => July 21 2020
[y] => 0
)
)
This will take quadratic time, if you need something faster you will have to change the indices of your arrays to make a faster lookup.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: invalid argument supplied for foreach() laravel
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.