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:

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

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改