“ message”:“非法字符串偏移'product_id'”,“ exception”:“ ErrorException”,

问题描述

$ json = file_get_contents('PHP:// input');

        // Decode the received JSON and store into $obj
        $obj = json_decode($json,true);

        foreach($obj as $product){
          $product_id = $product['product_id'];
          $data=array("product_id"=>$product_id);
          DB::table('order_products')->insert($data); 
        }

解决方法

foreach循环中$product里面是什么?

示例:

如果其值为array( product_id => 1 ),则$product['product_id']的结果为1

但是如果出现错误,并且$product例如{"product_id":1}(字符串而不是数组),则$product['product_id']的结果将是错误。

可能的解决方法:

您可以在foreach循环内尝试$product = json_decode($product,true);,也许$product未被解码,仍然是字符串,因此可以解决您的问题。