我收到错误非法字符串偏移' requestId'

时间:2016-07-09 20:50:06

标签: php json html5 multidimensional-array

我使用API​​,它在json中返回我的网址中的一些数据:

这是实际的网址数据:

data={%22requestId%22%3A%22546b384ce51f469a2e8b4567%22%2C%22numbers%22%3A{%22917566559950%22%3A{%22date%22%3A%222014-11-18+17%3A45%3A59%22%2C%22status%22%3A1%2C%22desc%22%3A%22DELIVERED%22}}}

我的PHP代码用于将数据插入数据库但收到错误:

$request = $_REQUEST["data"];
$jsonData = json_decode($request,true);
$link = mysqli_connect("127.0.0.1", "root", "", "table");
 foreach($jsonData as $key => $value)
 {
  $requestID = $value['requestId'] ;
  $userId = $value['userId'];
   $senderId = $value['senderId'];
    foreach($value['report'] as $key1 => $value1)
      {
    //detail description of report
    $desc = $value1['desc'];
    // status of each number
    $status = $value1['status'];
    // destination number
    $receiver = $value1['number'];
    //delivery report time
    $date = $value1['date'];
    $query = "INSERT Query for store record ";
    mysqli_query($link, $query);
}
 }

这里的问题是什么错误 警告:非法字符串偏移' requestId'在第11行 警告:非法字符串偏移' userId' ..... 请解决它....

1 个答案:

答案 0 :(得分:1)

<强> TLDR;

You should remove the foreach($jsonData as ...) around your code.

您正在使用它的键来预处理这个关联数组:

{  
"requestId":"546b384ce51f469a2e8b4567",
"numbers":{  
   "917566559950":{  
     "date":"2014-11-18 17:45:59",
     "status":1,
     "desc":"DELIVERED"
  }
 }
}

第一次迭代,密钥为“requestId”,值字段为“546b384ce51f469a2e8b4567”。在第二轮你得到了“数字”和上面的数组。

$requestID = $jsonData['requestId'];
var_dump($requestID); // the requestID


// foreaching in the assoc array inside the 'numbers'
foreach ($jsonData["numbers"] as $key => $value) {
  // description
  $desc = $value['desc'];
  // status of each number
  $status = $value['status'];
  // date
  $date = $value['date'];    

  var_dump($key); // the key with 917...
}