简体   繁体   English

如何在php中解析带有数组的JSON字符串

[英]How to parse JSON string with array in php

I am sending a JSON string in php post request. 我在php post请求中发送JSON字符串。 JSON string look like this: JSON字符串如下所示:

{"mobile":"0000000000","otp":"970996", "items":[{"pid":"12", "vid":"20"},{"pid":"13", "vid":"2"}]}

At server side i want to get mobile, otp and pid and vid for all items. 在服务器端,我想为所有项目获取移动,OTP,PID和vid。

I am getting mobile number from this: 我从这里得到手机号码:

$data = json_decode(file_get_contents('php://input'), true);
//print_r($data);
echo $data["mobile"];

But when i am trying to get pid and vid like this: 但是当我试图像这样获取pid和vid时:

foreach($data["items"] as $mydata){

     echo $mydata->pid;
}

i am getting error: Trying to get property of non-object. 我收到错误:尝试获取非对象的属性。

How to solve this? 如何解决呢?

Edit: 编辑:

If there is any better way to parse JSON in php, please suggest that also. 如果有更好的方法来解析php中的JSON,请同时提出。

Just access pid with: 只需使用以下命令访问pid

$mydata['pid']

You pass true as a second argument for json_decode 您将true作为json_decode的第二个参数json_decode

When TRUE, returned objects will be converted into associative arrays. 如果为TRUE,则返回的对象将转换为关联数组。

So you have to treat is as an array, not an object. 因此,您必须将其视为数组,而不是对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM