如何在laravel中打印与其类别名称相关的品牌名称?

xzlaal3s  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(537)

使用laravel5.6和mysql。我有如下表名 vehicles

id  name  categoryname  brandname    model
1   juy   car           toyota       121
2   gty   van           nissan       caravan
3   bgh   car           bmw          520d
4   hyu   van           ford         max
5   nhj   car           toyota       121

现在我需要单独打印每个品牌的名字和相关的类别名称,就像这样,

car
toyota
bmw

van
nissan
ford

如何在控制器中执行此操作?

mnowg1ta

mnowg1ta1#

尝试此代码

$vehicles = DB::table('vehicles')
                    ->orderBy('categoryname', 'asc')
                    ->get();

    $cat = "";
    foreach($vehicles AS $vehicle) {
        if($vehicle->categoryname != $cat) {
            $cat = $vehicle->categoryname;
            echo $cat . '<br><br>';
        }

        echo $vehicle->brandname . '<br>';
    }
jdgnovmf

jdgnovmf2#

$vehicles = DB::table('vehicles')->get();

$arr = [];

foreach($vehicles as $veh)
{
    if(isset( $arr[$veh->categoryname] ))
    {
       $arr[$veh->categoryname][] = $veh->brandname;
    } else 
    {
       $arr[$veh->categoryname][] = $veh->categoryname;
    }     

}

dd($arr);

相关问题