0

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"];
}
2
  • 2
    Did you try anything? Or you expect us to write code for you? Commented Nov 11, 2016 at 13:46
  • Your edit is not what you tried but how you build your arrays. Commented Nov 11, 2016 at 13:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks. Works! There is only a problem.... How can I choose if the value is NULL? I tried with this code but without success: foreach($result as $key => $value){ if( $value > 0) { echo "<td class=\"danger\">In errore</td>"; }elseif($value == 0) { echo "<td class=\"success\">Tutto OK</td>"; } elseif($value == "N/D") { echo "<td></td>"; } }
use : elseif($value === NULL) to match against NULL value. No problem. Happy Coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.