合并来自foreach循环的多个数组

时间:2015-12-29 02:07:46

标签: php mysql arrays foreach merge

我正在尝试从数据库获取开始和结束日期,生成开始和结束之间的范围日期,创建一个数组,以便我可以在datepicker中禁用它们。问题是我得到了多个阵列。如何将它们合并为一个数组?

这就是我所拥有的:

$datestartend = mysql_query("SELECT * FROM booking");
 while ($result = mysql_fetch_array($datestartend)){


$begin = new DateTime($result['tdate']);
$end = new DateTime($result['ldate']);

$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $end);

 $range = [];
foreach ($dateRange as $date) {
    $range[] = $date->format('d-m-Y');
  }

echo json_encode($range);


 }

这就是我得到的:

["11-11-2016","12-11-2016","13-11-2016","14-11-2016"]["11-02-2016","12-02-2016","13-02-2016","14-02-2016","15-02-2016","16-02-2016"]["22-08-2016","23-08-2016","24-08-2016","25-08-2016","26-08-2016","27-08-2016","28-08-2016","29-08-2016"]["21-10-2016","22-10-2016","23-10-2016","24-10-2016","25-10-2016","26-10-2016","27-10-2016","28-10-2016","29-10-2016","30-10-2016"]

这就是我想要的:

  ["11-11-2016","12-11-2016","13-11-2016","14-11-2016","11-02-2016","12-02-2016","13-02-2016","14-02-2016","15-02-2016","16-02-2016","22-08-2016","23-08-2016","24-08-2016","25-08-2016","26-08-2016","27-08-2016","28-08-2016","29-08-2016","21-10-2016","22-10-2016","23-10-2016","24-10-2016","25-10-2016","26-10-2016","27-10-2016","28-10-2016","29-10-2016","30-10-2016"]

1 个答案:

答案 0 :(得分:0)

我认为这不会给你想要的结果,因为每个循环$sql = "SELECT * FROM ".USERS." "; $result = $site_db->query($sql); $user_id = array(); while ($user_row = $site_db->fetch_array($result)) { array_push($user_id, $user_row['user_id']); } //then you can use your array now foreach ($user_id as $value) { echo "$value <br>"; } 都会产生一个空数组。 然后用数据填充数组,然后回显数据$range = [];

在下一个循环中,前一个循环将再次发生,这就是您看到多个数组符号的原因。

echo json_encode($range);数组移到while循环之外并在while循环之后将此语句$range = [];移到右侧时,这可能会有所帮助。

例如:

echo json_encode($range);