循环数组并通过组合两个数组创建新数组

时间:2016-11-14 05:40:04

标签: php

$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)
);

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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);