[英]How do I loop a nested array in laravel to get an array based on conditions of key values from that array
I want to get only the arrays where the option is not null When i get the arrays back successfully, i also want to add it to a database, but most importantly i want to get the arrays back我只想获取选项不为空的数组当我成功取回数组时,我还想将其添加到数据库中,但最重要的是我想取回数组
array:3 [
0 => array:5 [
"id" => 6
"option" => "True"
"is_correct" => true
"label" => "True"
"opid" => 1
]
1 => array:5 [
"id" => 7
"option" => "False"
"is_correct" => false
"label" => "False"
"opid" => 1
]
2 => array:5 [
"id" => 8
"option" => null
"is_correct" => false
"label" => "Theory"
"opid" => 5
]
]
EXPECTED RESULT预期结果
array:3 [
0 => array:5 [
"id" => 6
"option" => "True"
"is_correct" => true
"label" => "True"
"opid" => 1
]
1 => array:5 [
"id" => 7
"option" => "False"
"is_correct" => false
"label" => "False"
"opid" => 1
]
]
WHAT I HAVE TRIED我的尝试
foreach($request->option as $option) {
if($option["option"] == null){
dd($option)
}
}
i only get the first value from the array.. it appears like my if condition is not working as well我只从数组中获取第一个值.. 看起来我的 if 条件不起作用
i'll be in the comments thank you我会在评论中谢谢你
Try except
method,尝试except
方法,
Read documentation - https://laravel.com/docs/8.x/eloquent-collections#method-contains阅读文档 - https://laravel.com/docs/8.x/eloquent-collections#method-contains
Suppose if your $request->option
contain array then假设您的$request->option
包含数组,则
$filtered = collect($request->option)->whereNotNull('option')->all()->toArray();
Ref: https://laravel.com/docs/8.x/collections#method-wherenotnull参考: https : //laravel.com/docs/8.x/collections#method-wherenotnull
Use $z
variable, it contains the array as per your requirement.使用$z
变量,它根据您的要求包含数组。
Demo: https://paiza.io/projects/FTTBeEEnb-EHHJbU8FOAYw演示: https : //paiza.io/projects/FTTBeEEnb-EHHJbU8FOAYw
$x = [
[
"id" => 6,
"option" => "True",
"is_correct" => true,
"label" => "True",
"opid" => 1
],
[
"id" => 7,
"option" => "False",
"is_correct" => false,
"label" => "False",
"opid" => 1
],
[
"id" => 8,
"option" => null,
"is_correct" => false,
"label" => "Theory",
"opid" => 5
]
];
$z = [];
foreach ($x as $y) {
if ($y['option'] != null) {
array_push($z, $y);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.