I have two different arrays
Array 1:
$result = array(
"2018-08-30" => 8
"2018-08-31" => 2
"2018-09-04" => 4
"2018-09-20" => 1
"2018-09-24" => 1
"2018-09-27" => 2
);
and
Array 2
$dateRanges = array(
"2018-08-28" => 0
"2018-08-29" => 1
"2018-08-30" => 2
"2018-08-31" => 3
"2018-09-01" => 4
"2018-09-02" => 5
"2018-09-03" => 6
"2018-09-04" => 7
"2018-09-05" => 8
"2018-09-06" => 9
"2018-09-07" => 10
"2018-09-08" => 11
"2018-09-09" => 12
"2018-09-10" => 13
"2018-09-11" => 14
"2018-09-12" => 15
"2018-09-13" => 16
"2018-09-14" => 17
"2018-09-15" => 18
"2018-09-16" => 19
"2018-09-17" => 20
"2018-09-18" => 21
"2018-09-19" => 22
"2018-09-20" => 23
"2018-09-21" => 24
"2018-09-22" => 25
"2018-09-23" => 26
"2018-09-24" => 27
"2018-09-25" => 28
"2018-09-26" => 29
"2018-09-27" => 30
);
I have used array_flip for second array($dateRanges), so please dont get confused the the values give in the sequence.
I want to assign the value of the date from Array1 to Array2;
expected result :
$dateRanges = array(
"2018-08-28" => 0
"2018-08-29" => 0
"2018-08-30" => 8
"2018-08-31" => 2
"2018-09-01" => 0
"2018-09-02" => 0
"2018-09-03" => 0
"2018-09-04" => 4
"2018-09-05" => 0
"2018-09-06" => 0
"2018-09-07" => 0
"2018-09-08" => 0
"2018-09-09" => 0
"2018-09-10" => 0
"2018-09-11" => 0
"2018-09-12" => 0
"2018-09-13" => 0
"2018-09-14" => 0
"2018-09-15" => 0
"2018-09-16" => 0
"2018-09-17" => 0
"2018-09-18" => 0
"2018-09-19" => 0
"2018-09-20" => 1
"2018-09-21" => 0
"2018-09-22" => 0
"2018-09-23" => 0
"2018-09-24" => 1
"2018-09-25" => 0
"2018-09-26" => 0
"2018-09-27" => 2
);
I have done this using foreach loop where i am checking if my date is exists in $dateRanges
array, but I want to know if there are any shortcut way like using array_column
or array_combine
or array_walk
function.
Thanks
You can use combination of array_map()
and array_merge()
$newArr = array_merge(array_map(function($v){return 0;}, $dateRanges), $result);
Check result in demo
The following should work, copying values from $array1
to $array2
or setting 0
if no value exists.
I have not tested this code so a little tweaking might be necessary.
$array1 = array(/*...*/);
$array2 = array(/*...*/);
array_walk($array2, function (&$v, $k) use ($array1) {
if (isset($array1[$k]))
$v = $array1[$k];
else
$v = 0;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.