如何从外部数组获取内部数组

时间:2018-11-29 05:49:54

标签: php arrays json laravel api

我想从外部数组中提取一个数组。

我的结果

enter image description here

我要删除数组的圆形符号

{
"Success": "1",
"Message": "Subtopic Wise Questions...",
"Subtopic Questions": [
    [
        {
            "id": "93",
            "topic_id": "36",
            "name": "Cell membrane and organelle",
            "created_at": "2018-08-29 23:06:34",
            "updated_at": "2018-08-29 23:06:34",
            "q_count": "127"
        }
    ],   
]

}

这是我的数组输出结果。

我的控制器代码

 foreach($findid as $v)
        {
            $count[] = DB::table('questions')
                        ->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
                        ->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
                        ->where('subtopic_id', $v)
                        ->get();
        }


        return response([
                    'Success' => "1",
                    'Message' => "Subtopic Wise Questions...",
                    'Subtopic Questions'   => $count
                    ]); 

3 个答案:

答案 0 :(得分:2)

根据您要删除多余的数组引号的图像,使用first()仅获取一个对象

$count[] = DB::table('questions')
                    ->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
                    ->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
                    ->where('subtopic_id', $v)
                    ->first();

希望对您有帮助!

答案 1 :(得分:1)

使用whereIn方法代替where方法

  

仅将id存储在数组中,然后使用whereIn方法

$count = DB::table('questions')
                ->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
                ->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
                ->whereIn('subtopic_id', array_wrap($findid))
                ->get();
  

请注意,如果不能按您希望的方式工作,请在其中添加toArray()方法   这样的查询

$ count-> toArray();

 return response([
               'Success' => "1",
               'Message' => "Subtopic Wise Questions...",
               'Subtopic Questions'   => $count
     ]);

答案 2 :(得分:0)

您的查询很昂贵。由于您要遍历ID数组,因此将要运行count(findid)次查询。您可以优化并达到与

相同的效果
$count = DB::table('questions')
            ->join('subtopics', 'subtopics.id', 'questions.subtopic_id')
            ->select('subtopics.*', DB::raw('count(questions.id) as q_count'))
            ->whereIn('subtopic_id', $findid)
            ->get();


return response([
    'Success' => "1",
    'Message' => "Subtopic Wise Questions...",
    'Subtopic Questions'   => $count
]);