2016-11-14 213 views
1
$array1=Array("2016-11-02","2016-11-03","2016-11-04","2016-11-05","2016-11-06","2016-11-07","2016-11-08"); 

$array2 = Array([0] => Array("count" => 2 ,"created_at"=> 2016-11-04)); 

//期望的結果將環路一個陣列,並創建由新的數組組合兩個陣列

$array3 = Array(
    [0] => Array("count" => 0 ,"created_at" => 2016-11-02), 
    [1] => Array("count" =>0 "created_at" => 2016-11-03), 
    [2] => Array("count" => 2 ,"created_at" => 2016-11-04), 
    [3] => Array("count" => 0 ,"created_at" => 2016-11-05), 
    [4] => Array("count" =>0 ,"created_at" => 2016-11-06), 
    [5] => Array("count" => 0 ,"created_at" => 2016-11-07), 
    [6] => Array("count" => 0 ,"created_at" => 2016-11-08) 
); 
+0

嘗試[array_merge()](HTTP: //www.w3schools.com/php/func_array_merge.asp) –

+0

如果將一個指令分隔符(;)放入數組中,您將會在php中出錯。 –

+0

也將逗號分隔數組中的每個項目。如果你不用逗號,你也會得到一個錯誤。 –

回答

0
$array1=array("2016-11-02","2016-11-03","2016-11-04","2016-11-05","2016-11-06","2016-11-07","2016-11-08"); 

$array4 = array(0 => array("count" =>'2' ,"created_at"=>'2016-11-04'),1 => array("count" =>'2' ,"created_at"=>'2016-11-05')); 

$array3 = array(); 

for($i =0;$i<count($array1); $i++) { 
    $array3[$i]['count'] = 0; 
    $array3[$i]['created_at'] = $array1[$i]; 
} 

$arr = array_merge($array3,$array4); 

foreach($arr as $k => $v) { 
    foreach($arr as $key => $value) { 
     if($k != $key && $v['created_at'] == $value['created_at']) { 
      unset($arr[$k]); 
     } 
    } 
} 

$arr = array_values($arr); 

function date_compare($a, $b) { 
    $t1 = strtotime($a['created_at']); 
    $t2 = strtotime($b['created_at']); 
    return $t1 - $t2; 
} 

usort($arr, 'date_compare'); 

print_r($arr); 
0

嘗試此 -

foreach ($array1 as $date) { 
    //if value resides in $array2 - use that count 
    if (in_array($date, $array2[0])) { 
    $array3[]['count'] = $array2[0]['count']; 
    } 
    else { 
    $array3[]['count'] = 0; 
    } 
    $array3[]['created_at'] = $date; 
} 

print_r($array3); //should be your required array.