douvcpx6526 2016-04-03 13:32
浏览 99
已采纳

如何使用LEFT JOIN mysql查询轻松地在PHP中拆分结果?

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?

  • 写回答

1条回答 默认 最新

  • dongmo8943 2016-04-03 17:57
    关注

    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:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.