[英]How to Echo JSON string
I want to echo/print a JSON string, here is what I have tried. 我想回显/打印JSON字符串,这是我尝试过的。
I have decoded as it returns associative array. 我已经解码,因为它返回了关联数组。
$decoded = json_decode('{"Title": "The Cuckoos Calling",
"Author": "Robert Galbraith",
"Detail": {
"Publisher": "Little Brown"
}}', true/* returns Associative Array */);
foreach ($decoded as $head => $inner) {
echo $head . ': </br>';
}
It only prints... 它只打印...
Title:
Author:
Detail:
Here is what I want... 这就是我想要的...
Expected Output :
Title : The Cuckoos Calling
Author : Robert Galbraith
EDIT: 编辑:
Its print_r()
output is. 其
print_r()
输出为。
Array ( [Title] => The Cuckoos Calling [Author] => Robert Galbraith [Detail] => Array ( [Publisher] => Little Brown ) )
And var_dump()
is var_dump()
是
array (size=3)
'Title' => string 'The Cuckoos Calling' (length=19)
'Author' => string 'Robert Galbraith' (length=16)
'Detail' =>
array (size=1)
'Publisher' => string 'Little Brown' (length=12)
have you noticed that you are only printing the $key and not the value ??? 您是否注意到您仅打印$ key而不是值???
foreach ($decoded as $head => $inner) {
echo $head . ': '. $inner . '</br>';
}
this is what you need : 这就是您需要的:
function arrayToUl($array)
{
$out = "<ul>";
foreach ($array as $key => $value) {
$value_string = $value;
if (is_array($value))
$value_string = arrayToUl($value);
$out .= "<li>{$key} : {$value_string}</li>";
}
$out .= "</ul>";
return $out;
}
echo arrayToUl($decoded);
simply use array_walk_recursive 只需使用array_walk_recursive
array_walk_recursive($decoded, function($key,$value) {
echo $value.' :'.$key.'<br>';
});
output : 输出 :
Title :The Cuckoos Calling
Author :Robert Galbraith
Publisher :Little Brown
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.