我尝试使用json_decode
将json数组解码为php数组,但它显示的是空白页
这里是json数组
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
这里是解码json的代码
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
由于
答案 0 :(得分:2)
虽然您的代码看起来正确,但您的JSON数据无效。对象由{}
括起,而不是[]
。用这个替换JSON,它应该可以工作。
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
答案 1 :(得分:2)
要使用JSON
和json_decode()
获取正确的json_encode()
,请遵循以下准则:
json_decode():
此功能仅适用于UTF-8编码的字符串。
以适当的PHP类型返回json中编码的值。值true,false和null分别返回为TRUE,FALSE和NULL。如果无法解码json或编码数据深于递归限制,则返回NULL。
键和值必须用双引号括起来。单引号无效。
你的JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears无效。 Arrays
使用[]
而objects
使用{}
。
这是在执行json_encode()
之前(发送之前)正确的PHP数组结构的示例:
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
使用以下方法获得:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
这意味着这样做:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
有效JSON
看起来像这样:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
如果要从数据库获取数据,可能需要使用以下内容:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
答案 2 :(得分:1)
以上答案已经提到过: 您的JSON无效。你可以检查一下,例如使用像https://jsonlint.com/
这样的JSON linter另外,您使用$names = $data['result'];
引用了名称。但是,在您提供的JSON中,没有数组(或更好的对象),键为“result”。
您可以查找PHP的错误日志文件以了解问题所在。