[英]Create multidimensional arrays using single table
I have a table like this; 我有这样一张桌子;
**Year** **Month**
2012 Jan
2012 Mar
2012 Apr
2013 Dec
2013 Nov
And I am trying to create an array from this table similar to below; 我试图从这个表创建一个类似于下面的数组;
Array
(
[2012] => Array(
Jan, Mar, Apr),
[2013] => Array(
Dec, Nov)
);
so far I tried this code, but didn't get what I want, 到目前为止我尝试了这段代码,但没有得到我想要的,
while ($row = mysql_fetch_array($result)){
$new_array[] = array(
'year' => $row['year'],
'month' => $row['month'],
);
}
Try this 尝试这个
while ($row = mysql_fetch_array($result)){
$new_array[$row['year']][] = $row['month'];
}
A better solution would be using MySQL's GROUP_CONCAT
and GROUP
to create a result of a row per year, then use PHP's explode
to split the GROUP_CONCAT
enated value to an array: 更好的解决方案是使用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']);
}
Change your while
loop to this: 将while
循环更改为:
while ($row = mysql_fetch_array($result)){
$new_array[$row['year']][] = $row['month'];
}
Try the below line create the array in outside the loop. 尝试下面的行在循环外部创建数组。
$newArray=array();
while($row=mysql_fetch_array($(result))
$newArray[$row['year']] = $row['month'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.