我有一个这样的表;
**Year** **Month**
2012 Jan
2012 Mar
2012 Apr
2013 Dec
2013 Nov
和我试图创建一个数组从这个表类似于下面;
Array
(
[2012] => Array(
Jan, Mar, Apr),
[2013] => Array(
Dec, Nov)
);
到目前为止,我尝试了这个代码,但没有得到我想要的,
while ($row = mysql_fetch_array($result)){
$new_array[] = array(
'year' => $row['year'],
'month' => $row['month'],
);
}
试试这个
while ($row = mysql_fetch_array($result)){
$new_array[$row['year']][] = $row['month'];
}
一个更好的解决方案是使用MySQL的GROUP_CONCAT
和GROUP
每年创建一行的结果,然后使用PHP的explode
将GROUP_CONCAT
生成的值分割到一个数组:
$query = mysql_query("SELECT `year`, GROUP_CONCAT(`month`) AS `months` FROM table GROUP BY `year`");
$new_array = array();
while ($row = mysql_fetch_array($result)) {
$new_array[$row['year']] = explode(',', $row['months']);
}
$new_array=array();
while ($row = mysql_fetch_array($result)){
if(!isset($new_array[$row['year']])
$new_array[$row['year']]=array();
$new_array[$row['year']] = array_push($new_array[$row['year']],$row['month']);
}
试试下面一行在循环外创建数组
$newArray=array();
while($row=mysql_fetch_array($(result))
$newArray[$row['year']] = $row['month'];
将while
循环改为:
while ($row = mysql_fetch_array($result)){
$new_array[$row['year']][] = $row['month'];
}