[英]SQL Results as PHP Array
How do I get a SQL result that will contain multiple rows into an array:如何获得 SQL 结果,该结果将在数组中包含多行:
Example SQL Table:示例 SQL 表:
ID Cat LineID Qty DealID Cost
1 Phone 1 2 8941 25.00
2 Phone 2 43 8941 85.00
3 Net 1 2 8941 1.00
4 App 1 1 8941 87.00
5 Phone 1 20 8942 98.00
Would like to be able to return the result like:希望能够返回如下结果:
$product[Phone][LineID][Qty]
$product[Phone][1][Qty] -- this would return 2
BTW: Within a Cat the LineID would never be duplicated, but it may not alway be the same LineID's - for Example under DealID 8941 there might be LineID for Cat>Phones 1,2,3,4 but under a different DealID there might only be Cat>Phones 4,5顺便说一句:在 Cat 中,LineID 永远不会重复,但它可能并不总是相同的 LineID - 例如,在 DealID 8941 下,Cat>Phones 1、2、3、4 可能有 LineID,但在不同的 DealID 下,可能只有成为猫>电话 4,5
Not sure if I'm barking up the complete wrong tree, basicly I need to loop through all the results under a DealID then cross reference the LineID to get all the information about that LineID from a another table which holds the name, image etc...Then put into a html table along the lines of:不确定我是否在吠叫完全错误的树,基本上我需要遍历 DealID 下的所有结果,然后交叉引用 LineID 以从另一个包含名称、图像等的表中获取有关该 LineID 的所有信息。 ..然后按照以下方式放入html表中:
Product Name Qty Cost Line Total
Phone 1 1 85.00 85.00
I hope I have made this clear, if not don't be too harsh!!我希望我已经说清楚了,如果不是太苛刻的话!!
Thanks, B.谢谢,B。
$array = array();
while ($row = mysql_fetch_assoc($query_result)) {
$array[$row['Cat']][$row['LineID']] = array(
'Qty' => $row['Qty'],
'DealID' => $row['DealID'],
'Cost' => $row['Cost']
);
}
This will look through your array and create an array of the structure you described.这将查看您的数组并创建您描述的结构的数组。 Note that I assume you'll want all the remaining fields available under the two indices you mentioned, not just
Qty
.请注意,我假设您希望您提到的两个索引下的所有剩余字段都可用,而不仅仅是
Qty
。 Another solution, quicker, but larger in memory, would have been:在 memory 中,另一个更快但更大的解决方案是:
$array[$row['Cat']][$row['LineID']] = $row;
This would have put every value there, including the Cat
and LineID
values that were just used.这会将每个值都放在那里,包括刚刚使用的
Cat
和LineID
值。
Have a look at mysql_fetch_assoc
.看看
mysql_fetch_assoc
。
http://php.net/manual/en/function.mysql-fetch-assoc.php http://php.net/manual/en/function.mysql-fetch-assoc.php
you need to use the php function mysql_fetch_array()你需要使用 php function mysql_fetch_array()
This is the answer:这是答案:
$sql="SELECT * FROM Blar";
$result = mysql_query($sql);
$combinedResults = array();
while ($row = mysql_fetch_array($result)) {
$combinedResults[$row['cat']][] = array(
'LineID' => $row['lineID'],
'Qty' => $row['qty'],
'SetCost' => $row['Setcost'],
'MonCost' => $row['Moncost'],
'Postcode' => $row['postcode']
);
};
//print_r($combinedResults);
print_r($combinedResults['Apps'][0]['Qty']);
Thanks for your help @Dereleases感谢您的帮助@Dereleases
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.