简体   繁体   中英

How to easily split results in PHP with a LEFT JOIN mysql query?

I have a query in which I am tring to put the results in an array. The query returns all data of the two tables: order and orderdetails :

SELECT orders.*, order_details.* FROM `webshop_orders` 
        LEFT JOIN `order_details` 
        ON `orders`.`order_id` = `order_details`.`f_order_id` 
        WHERE `orders`.`f_site_id` = $iSite_id AND `orders`.`order_id` = $iOrder_id;";

I am trying to found out how to return this data an put them in an array of the following format:

$aOrders = array(
0=>array(Orders.parameter1=>value, orders.parameter2=>value, orders.parameter3=>value, 'orderdetails'=>array(
    array(Orderdetails.parameter1=>value, orderdetails.parameter2=>value)));

I currently return every result as an associate array and manually split every variable based on its name using 2 key-arrays, but this seems very 'labor-intensive'?

while($aResults = mysql_fetch_assoc($aResult)) { 
    $i++;
    foreach($aResults as $sKey=>$mValue){
        if(in_array($sKey, $aOrderKeys){
            $aOrder[$i][$sKey] = $mValue;
        } else {
            $aOrder[$i]['orderdetails'][$sKey] = $mValue;
        }
    }
}

EDIT: the function above does not take multiple order-details into consideration, but the function is meant as an example!

Is there an easier way or can I use a better query for this?

You can use the following while loop to fill your array:

$data = array();
while ($row = mysql_fetch_assoc($result)) {
    if (!isset($data[$row['order_id']])) {
        $order = array('order_id' => $row['order_id'],
                       'order_date' => $row['order_date'],
                       /* ... */
                       'orderdetails' => array());
        $data[$row['order_id']] = $order;
    }
    if (isset($row['order_details_id'])) { // or is it "!= null"? don't know...
        $details = array('id' => $row['order_details_id'],
                         'whatever' => $row['order_details_whatever']);
        $data[$row['order_id']]['orderdetails'][] = $details;
    }
}

This way you can have multiple orderdetails for one order, they get all added to the ['orderdetails'] field.

Additional notes:

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