我现在正在使用Laravel 5,我遇到了以下问题。我收到了DB查询的回复:
[{"id":1}]
我想取1作为int或string。有什么想法吗?
我试着解决这个问题如下:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
响应为:
json_decode()期望参数1为字符串,给定的数组
这就是您所需要的。
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
正如您所说,您拥有的字符串是JSON格式的,因此您需要使用json_decode
在PHP中访问它。
方括号表示一个数组,大括号表示该数组中的一个对象,因此您要查找的是数组中第一个元素(即元素0
)的id
值。
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
试试这个
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
如果我没有误解你的问题,你只需要解码它。
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
然后你可以在aray中循环,并对你的数据进行处理:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
如果你使用的是Laravel,为什么不使用Eloquent模型呢?