如何从外部数组中获取内部数组
Posted
技术标签:
【中文标题】如何从外部数组中获取内部数组【英文标题】:how to get inner array from Outer array 【发布时间】:2019-05-01 03:21:48 【问题描述】:我想从外部数组中拉出一个数组。
我的结果
我要删除数组的圆圈符号
"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
]);
【问题讨论】:
使用$count
而不是$count[]
使 foreach 循环通过 Subtopic Questions->Subtopic Questions
@JigneshJoisar 如果我使用 $count 它只返回结果的第一列。
在我看来,您应该尝试一次获取所有必需的行,而不是每次获取一个。
【参考方案1】:
您的查询很昂贵。由于您正在遍历 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
]);
【讨论】:
【参考方案2】:使用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
]);
【讨论】:
可以用array_wrap($findid)
替换is_array($findid) ? $findid : [ $findid]
【参考方案3】:
使用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();
希望对你有帮助!
【讨论】:
@KrishBhardwaj Eloquent 将在您显示结果时返回一个对象数组,如果您不使用toArray()
,则清楚地表明它是一个对象数组。因此,如果您只想拉数组而不是对象,则需要使用toArray()
我曾经使用 toArray() 但无法达到我的效果。
哦,好吧,我明白了!请检查我编辑的答案。 @KrishBhardwaj
@KrishBhardwaj QueryBuilder 将返回 Illuminate\Support\Collection
。 @LeenaPatel Eloquent 将返回 `Illuminate\Database\Eloquent\Collection。不是数组或对象数组。以上是关于如何从外部数组中获取内部数组的主要内容,如果未能解决你的问题,请参考以下文章