【问题标题】:Laravel arrays and foreachLaravel 数组和 foreach
【发布时间】:2016-08-24 14:50:58
【问题描述】:

所以我通过 POST 请求从 Ionic 应用程序向 API 发送一系列调味品,这些调味品在移动部件上表示为复选框。我想获得选中的复选框,以便我可以相应地创建表格行。

路由触发时调用的方法有这部分:

$condiments = Input::only('condiments');

foreach ($condiments as $condiment) {
        if ($condiment['checked'] == 1) {
            OrderCondiment::create(['order_item_id' => $orderItem, 
                                    'condiment_id' => $condiment->id]);
        }
}

但我收到Illegal string offset 'checked' 错误。我尝试使用$condiment->checked,但后来我得到Trying to get the property of non-object 错误...我错过了什么...除了咖啡

编辑

dd($condiments)

array:1 [
  "condiments" => "[{"id":1,"name":"ut","price":3,"created_at":null,"updated_at":null,"checked":1},{"id":2,"name":"ipsam","price":5,"created_at":null,"updated_at":null,"checked":1},{"id":3,"name":"dolores","price":10,"created_at":null,"updated_at":null,"checked":1},{"id":4,"name":"esse","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":5,"name":"aliquid","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":6,"name":"sunt","price":3,"created_at":null,"updated_at":null,"checked":0},{"id":7,"name":"saepe","price":1,"created_at":null,"updated_at":null,"checked":0},{"id":8,"name":"impedit","price":10,"created_at":null,"updated_at":null,"checked":0},{"id":9,"name":"dolores","price":4,"created_at":null,"updated_at":null,"checked":0},{"id":10,"name":"veniam","price":2,"created_at":null,"updated_at":null,"checked":0}]"
]

【问题讨论】:

  • dd('$condiments) 显示什么?
  • Input 中的任何内容都是一个数组;你不能这样做$condiment->id 它应该是:$condiment['id']
  • 是的,但是在“if”子句所在的行上出错了
  • 好吧,@AlexeyMezenin 是对的,您应该使用 dd 进行一些调试。
  • 老兄...我正在努力解决最后 2 小时的问题,在被卡住 5 分钟后我没有来这里...

标签: arrays laravel foreach


【解决方案1】:

字符串转数组

$condiments = Input::only('condiments');
$condiments= json_decode( $condiments['condiments']) ;
foreach ($condiments as $condiment) {
    if ($condiment->checked == 1) {
        OrderCondiment::create(['order_item_id' => $orderItem, 
                                'condiment_id' => $condiment->id]);
    }
}

【讨论】:

  • 不能使用 stdClass 类型的对象作为数组 -> 第 32 行的错误(“if”子句所在的位置)
  • 使用 $condiment->checked 代替 $condiment['checked']
猜你喜欢
  • 1970-01-01
  • 2015-04-24
  • 2019-04-17
  • 2019-02-09
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-26
相关资源
最近更新 更多