我有一个MySQL表,其中包含股票信息,包括股票所属的主要行业和子行业(例如可口可乐股票属于行业“消费品”和子行业“饮料 - 软饮料” ”
$SQL = "SELECT name, industrysector, subsector FROM Stocks WHERE economic_indicator_type = 'Stock' GROUP BY industrysector, subsector, name";
$result = mysql_query($SQL) or die ("Error in query: $SQL. " . mysql_error());
while ($row = mysql_fetch_row($result)) {
$stocks[$i]['name'] = $row[0];
$stocks[$i]['industrysector'] = $row[1];
$stocks[$i]['subsector'] = $row[2];
$i++;
}
$stocksTotals = array();
foreach($stocks as $amount) {
$stocksTotals[$amount['industrysector']] = $stocksTotals[$amount['industrysector']].", ".$amount['name'];
}
foreach($stocksTotals as $name => $amount) { echo $name.": ".substr($amount,1)."<br>"; }
我的问题是我没有得到处理第三级的代码。我想首先输出所有行业部门(例如基本材料),然后输出每个行业部门的所有子部门(例如基本资源),然后输出每个子部门对应的所有股票名称。
目前我只获得行业部门和股票名称,因为我无法理解如何在数组处理代码中处理这个问题。
任何建议都将受到高度赞赏!我在这里放了一张图片(http://imageshack.us/photo/my-images/853/mysqltophp.gif/)以便更好地参考。
谢谢!
答案 0 :(得分:0)
foreach
循环必须如下:
//considering you want the value as "$amount['industrysector'], $amount['name']"
foreach($stocks as $amount) {
// $stocksTotals[$amount['industrysector']] = $amount['industrysector'] .", ".$amount['name'];
echo $amount['industrysector'].": "."$amount['industrysector'], $amount['name']"."<br>";
}
你不需要另一个foreach循环。
编辑:您还需要更改获取行的方式,
while ($row = mysql_fetch_assoc($result)) {
$stocks[$i]['name'] = $row['name'];
$stocks[$i]['industrysector'] = $row['industrysector'];
$stocks[$i]['subsector'] = $row['industrysector'];
$i++;
}
foreach($stocks as $amount) {
$output = "$amount['industrysector'] : $amount['industrysector'], $amount['subsector']";
if( $amount['name'] !== '' )
$output .= "<br>" . $amount['name'];
";
}