【问题标题】:How to Pass multidimensional array to API using laravel如何使用 laravel 将多维数组传递给 API
【发布时间】:2021-03-25 04:32:13
【问题描述】:

我正在使用连接从两个表中获取数据,但是,我希望我的结果返回一个多维数组,即

水果

  • 苹果
  • 芒果
  • 橙色

动物

国家

  • 德国
  • 英国
  • 美国

所以,这就是我希望它返回的内容,请参阅下面的代码

 Route::get('all-category', function(){

$category = DB::table('directory_companies')
             ->join('categories','directory_companies.categories_id', '=', 'categories.id')
            ->select('categories.name', 'directory_companies.*') 
             ->get();
return response()->json($category);

我如何返回它以在多维数组中显示如上面的列表,我正在使用 Laravel 构建 API

【问题讨论】:

标签: php arrays json laravel api


【解决方案1】:

您可以使用eloquent resource 显示任何您想要的 api 结构。

创建资源和资源集合

php artisan make:resource directory_companies
php artisan make:resource directory_companies_collection --collection
$category = DB::table('directory_companies')
             ->join('categories','directory_companies.categories_id', '=', 'categories.id')
            ->select('categories.name', 'directory_companies.*') 
             ->get();

return response()
    ->json(new directory_companies_collection(new directory_companies($category)));

在您的 directory_companies 资源中:

public function toArray($request)
    {
        return [
            // Any structure of data you want to present
        ];
    }

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多