PHP優化 - 解決嵌套問題

在開發過程中,我們經常遇到一對多的場景,
例如:查詢訂單列表,並且展示訂單詳情商品、數量數據

思路0:傳統做法
  • a. 查詢訂單列表
  • b. 遍歷訂單詳情
	$orderList = select * from order where xx;
	foreach($orderList as $orderItem) {
		$orderItem->detailList = select * from order_detail where order_id = $orderItem->id;
	}
  • 分析:查詢SQL次數爲:N+1(N爲訂單個數),這樣頻繁請求數據庫,影響效率
  • 優化:減少頻繁請求數據庫
思路1:
  • a. 查詢訂單列表後,利用in查出所有訂單詳情
  • b. 通過(訂單表id => 訂單詳情表order_id)遍歷匹配數據
	$orderList = select * from order where xx;
	$orderId = array_pluck($orderList, 'id'); // Laravel內置數組輔助函數
	$orderDetailList = select * from order_detail where order_id IN $orderId;
	foreach($orderList as $orderItem) {
		$detailListTemp = [];
		foreach($orderDetailList as $orderDetailItem) {
			if ($orderItem->id == $orderDetailItem->order_id) {
				$detailListTemp[] = $orderDetailItem;		
			}
		}
		$orderItem->detailList = $detailListTemp;
	}
  • 分析:降低查詢後,但2層遍歷,複雜度較高,數量過大容易內存溢出
  • 優化:降低複雜度
思路2:
  • a. 查詢訂單列表後,利用in查出所有訂單詳情
  • b. 訂單詳情列表轉換成以訂單ID爲索引,用isset來匹配訂單的詳情
	$orderList = select * from order where xx;
	$orderId = array_pluck($orderList, 'id'); // Laravel內置數組輔助函數
	$orderDetailList = select * from order_detail where order_id IN $orderId;

	// 將訂單詳情轉換成以訂單ID爲索引【方式1】
	$orderDetailList = arrayGroup($orderDetailList, 'order_id');
	// 或:將訂單詳情轉換成以訂單ID爲索引【方式2:如果爲一對一,可以用array_column】
	// $orderList = array_column($orderDetailList, null, 'order_id'); 

	foreach($orderList as $orderItem) {
		$orderItem->detailList = $orderDetailList[$orderItem->id] ?? [];
	}

	// 根據KEY數組分組
	function arrayGroup($list, $key) {
	    $newList = [];
	    foreach ($list as $item) {
	        $newList[$item[$key]][] = $item;
	    }
	    return $newList;
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章