如何使用json laravel的单个键获取许多值?

时间:2018-11-06 13:30:56

标签: php mysql arrays json laravel

嗨,我想问一下如何在数组中发送json而不是一一发送。 我正在使用laravel和vue.js 我是laravel的新人,我想知道更多 我试图循环播放,但失败了

此处为示例:

{
    "data": [
        [
            {
                "activity_id": 1,
                "start_date": "2018-11-06",
                "product_name": "ks",
                "topic_name": "exploration"
            }
        ],
        [
            {
                "subproduct_name": "bcd"
            },
            {
                "subproduct_name": "cfr"
            }
        ]
    ]
}

我想让他们这样

{
    "data": [
        [
            {
                "activity_id": 1,
                "start_date": "2018-11-06",
                "product_name": "ks",
                "topic_name": "exploration",
                "subproduct_name":["bcd","cfr"]
            }
        ],

    ]
}

这是我的控制器

 public function getActivity()
{



    $getData = DB::table('new__businesses')->select('new__businesses.activity_id','new__businesses.start_date','new__businesses.end_date','new__businesses.corporate_name','ms__subsidiaries.subsidiary_name','ms__products.product_name','ms__topics.topic_name')
    ->leftjoin('ms__subsidiaries','ms__subsidiaries.subsidiary_id','=','new__businesses.subsidiary_id')
    ->join('ms__products','ms__products.product_id','=','new__businesses.product_id')
    ->join('ms__topics','ms__topics.topic_id','=','new__businesses.topic_id')
    ->get();

    $getSubproduct = DB::table('new__businesses')
        ->select('ms__subproducts.subproduct_name')
        ->join('store__subproducts','store__subproducts.activity_id','=','new__businesses.activity_id')
        ->join('ms__subproducts','ms__subproducts.subproduct_id','=','store__subproducts.subproduct_id')
        ->get();

    $getPic = DB::table('new__businesses')
        ->select('ms__users.user_name')
        ->join('pics','pics.activity_id','=','new__businesses.activity_id')
        ->join('ms__users','ms__users.user_id','=','pics.user_id')
        ->get();

        return response()->json([
            'data'=>$getData,
            'pic'=>$getPic,
            'subproduct'=>$getSubproduct
        ]);        


}

}

请给我解决方案,我被困住了

1 个答案:

答案 0 :(得分:0)

如果使用pluck而不是get,则会得到一个值数组,而不是对象数组,然后可以将其添加到数组中。

$getSubproduct = DB::table('new__businesses')
    ->join('store__subproducts','store__subproducts.activity_id','=','new__businesses.activity_id')
    ->join('ms__subproducts','ms__subproducts.subproduct_id','=','store__subproducts.subproduct_id')
    ->pluck('ms__subproducts.subproduct_name');