简体   繁体   中英

SQL Results as PHP Array

How do I get a SQL result that will contain multiple rows into an array:

Example SQL Table:

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

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:

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.

$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 . Another solution, quicker, but larger in memory, would have been:

    $array[$row['Cat']][$row['LineID']] = $row;

This would have put every value there, including the Cat and LineID values that were just used.

Have a look at mysql_fetch_assoc .

http://php.net/manual/en/function.mysql-fetch-assoc.php

you need to use the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM