2017-12-03 246 views
1

您好!我有一個需要輸出屏幕數據的查詢。
每個屏幕有4個展位可供展示。我需要一個查詢有一個結果(因爲我只有一個屏幕),並有4個展位(怎麼我分配的4個展位)在選擇查詢中選擇MYSQL

這裏是我的查詢:

$result = DB::select(" 
    SELECT 
     `A`.`scr_name`, 
     `A`.`mission_id`, 
     `B`.`booth_id`, 
     `E`.`name` 
    FROM `tbl_screen` `A` 
    LEFT JOIN 
     `tbl_screen_booths` `B` 
    ON `B`.`screen_id` = `A`.`id` 
    LEFT JOIN 
     `tbl_service_booths` `C` 
    ON `B`.`booth_id` = `C`.`id` 
    LEFT JOIN 
     `tbl_missions_services` `D` 
    ON `C`.`mission_services_id` = `D`.`id` 
    LEFT JOIN 
     `tbl_services` `E` 
    ON `D`.`service_id` = `E`.`id` 
    WHERE `A`.`mission_id` = $mission_id 
    GROUP BY 
     `B`.`booth_id`; 
"); 

return $result; 

我想是這樣這樣的:

"scr_name": "Test Screen", 
"mission_id": 2, 
"name": "booth1", //index[0] 
"name": "booth2", //index[1] 
"name": "booth3", //index[2] 
"name": "booth4" //index[4] 

我的查詢返回的是這樣的:

[ 
{ 
"scr_name": "Test Screen", 
"mission_id": 2, 
"booth_id": 7, 
"name": "booth1" 
}, 
{ 
"scr_name": "Test Screen", 
"mission_id": 2, 
"booth_id": 9, 
"name": "booth2" 
}, 
{ 
"scr_name": "Test Screen", 
"mission_id": 2, 
"booth_id": 10, 
"name": "booth3" 
}, 
{ 
"scr_name": "Test Screen", 
"mission_id": 2, 
"booth_id": 11, 
"name": "booth4" 
} 
] 

回答

1

結果還好..只是需要一點點迭代來獲取值..

$data['scr_name'] = $result[0]->scr_name; 
$data['mission_id'] = $result[0]-> mission_id; 

foreach($result as $index => $item) { 
    $data['name'.($index+1)] => $item->name; 
} 

結果:

"scr_name": "Test Screen", 
"mission_id": 2, 
"name1": "booth1", //index[0] 
"name2": "booth2", //index[1] 
"name3": "booth3", //index[2] 
"name4": "booth4" //index[4] 

數組鍵不能有相同的鍵名

+0

那會做訣竅,謝謝! –

+0

但是這不適合,如果我有多個屏幕,因爲它會返回多個結果。 –

+0

然後你需要迭代數據..把一些邏輯..然後產生輸出..這只是你的數據的示例 – ZeroOne