Francesco Esposto Francesco Esposto - 26 days ago 6
PHP Question

Check key's array with value's array and set it as value

I have a question for you.
My PHP code is composed by these below arrays and my intention is to merge them into one, as you can see at the bottom of the topic.
These arrays are divided into 2 different variables: $array1 and $array2.

Array ($array1)
(
[0] => 2016-11-11
[1] => 2016-11-10
[2] => 2016-11-09
[3] => 2016-11-08
[4] => 2016-11-07
[5] => 2016-11-06
[6] => 2016-11-05
)
1
Array ($array2)
(
[2016-11-11] => 0
[2016-11-10] => 0
[2016-11-08] => 0
[2016-11-07] => 0
[2016-11-06] => 0
)
1


And this is what I expect this program will do:

Array
(
[2016-11-11] => 0,
[2016-11-10] => 0,
[2016-11-09] => NULL,
[2016-11-08] => 0,
[2016-11-07] => 0,
[2016-11-06] => 0,
[2016-11-05] => NULL
)
1


How can I set my code so that it returns me the previous array? How can I solve this problem? Can anyone help me?

I tried:

$array1 = array(
"2016-11-11",
"2016-11-10",
"2016-11-09",
"2016-11-08",
"2016-11-07",
"2016-11-06",
"2016-11-05"
);
$array2 = array();
while($row1 = $result1->fetch_assoc())
{
$array2[$row1["datesend"]] = $row1["error"];
}

Answer

This code will work for you:

$array1 = array('2016-11-11','2016-11-10','2016-11-09','2016-11-08','2016-11-07','2016-11-06','2016-11-05');
$array2 = array('2016-11-11' => 0,'2016-11-10' => 0,'2016-11-08' => 0,'2016-11-07' => 0,'2016-11-06' => 0);

$result = array();
foreach($array1 as $a){
    if(isset($array2[$a]))
        $result[$a] = $array2[$a];
    else
        $result[$a] = NULL;
}
echo '<pre>';
var_dump($result);
echo '</pre>'

Outpur is:

array(7) {
  ["2016-11-11"]=>
  int(0)
  ["2016-11-10"]=>
  int(0)
  ["2016-11-09"]=>
  NULL
  ["2016-11-08"]=>
  int(0)
  ["2016-11-07"]=>
  int(0)
  ["2016-11-06"]=>
  int(0)
  ["2016-11-05"]=>
  NULL
}

I hope it helps