【问题标题】:How do I loop a nested array in laravel to get an array based on conditions of key values from that array如何在laravel中循环嵌套数组以根据该数组中键值的条件获取数组
【发布时间】:2021-09-27 21:19:24
【问题描述】:

我只想获取选项不为空的数组 当我成功取回数组时, 我也想将它添加到数据库中,但最重要的是我想找回数组

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
  ]
]

预期结果

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
      ]
    ]

我已经尝试过什么

foreach($request->option as $option) {
   if($option["option"] == null){
       dd($option)
    }
}

我只从数组中获取第一个值.. 看起来我的 if 条件不起作用

我会参加 cmets 谢谢你

【问题讨论】:

  • 你试过什么?
  • 您可以添加您尝试过的内容,以便有人可以帮助您解决
  • 好的,我会这样做的
  • 我已经添加了我尝试过的 John Lobo 和 user3532758

标签: php laravel multidimensional-array


【解决方案1】:

假设你的$request->option 包含数组,那么

$filtered = collect($request->option)->whereNotNull('option')->all()->toArray();

参考:https://laravel.com/docs/8.x/collections#method-wherenotnull

【讨论】:

    【解决方案2】:

    【讨论】:

    • 这不是我要找的
    • 很抱歉我的回答对你不起作用,你能详细说明一下你想要什么吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多