您可以通过以下两种方式之一来处理它:
1.使用GROUP_CONCAT(正如评论中提到的@Dave - 这是链接:MYSQL PHP API - Displaying & Fetching multiple rows within rows from another table)。但是有一个缺点, GROUP_CONCAT 有一个限制(默认为 1024 个字符),您可以使用服务器变量更改该限制group_concat_max_len
,但您可能无权这样做。
这看起来很像这样:
ID | Name | Car Model | Year
1 John BMW, Audi, Renault 1999, 2000, 2003
2 David Mercedes, Ford 2000, 2005
如果每个用户有 30-40 个条目并且不可读,这可能会变得非常复杂。
2.第二个选项是以以下格式导出它(不难做到,您只需遍历用户拥有的所有汽车,但仅在第一次迭代中写入用户)。
ID | Name | Car Model | Year
1 John BMW 1999
Audi 2000
Renault 2003
2 David .....
这是一些示例代码(我使用了很多编造的方法,这些方法具有暗示性的名称)。
$csvArray = array();
foreach ($users as $user) {
$cars = $user->getCars(); //random method name. Grabs an array with the cars this user has :)
$firstIteration = 1;
foreach ($cars as $car) {
if ($firstIteration == 1) { // we only set the CSV row the first time we iterate through cars
$csvSingle['ID'] = $user->getId(); // more random method names
$csvSingle['Name'] = $user->getName();
$firstIteration = 0;
}
$csvSingle['car_model'] = $car->getCarModel();
$csvSingle['car_year'] = $car->getCarYear();
$csvArray[] = $csvSingle; // now we add the single row to the big CSV array.
}
}
fputcsv($handle, $csvArray); // $handle is the file you export to