【问题标题】:How to Echo JSON string如何回显 JSON 字符串
【发布时间】:2014-07-14 04:26:14
【问题描述】:

我想回显/打印一个 JSON 字符串,这是我尝试过的。

我已经解码,因为它返回关联数组。

 $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>';
                }

它只打印...

Title: 
Author: 
Detail: 

这就是我想要的……

Expected Output :
Title  : The Cuckoos Calling
Author : Robert Galbraith

编辑:

它的print_r() 输出是。

Array ( [Title] => The Cuckoos Calling [Author] => Robert Galbraith [Detail] => Array ( [Publisher] => Little Brown ) )

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)

【问题讨论】:

标签: php html json


【解决方案1】:

你有没有注意到你只打印 $key 而不是值???

foreach ($decoded as $head => $inner) {
    echo $head . ': '. $inner . '</br>';
}

这就是你需要的:

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);

【讨论】:

  • 我试过这个..它打印标题和作者....但是该关联数组内还有另一个数组...请参阅我的问题中的 var_dump() 输出。
  • 为什么要使用 foreach 进行迭代?为什么不只呼应作者和标题?您想如何处理“详细信息”数组?
  • @UmairAyub 你如何处理内部数组?忽略它 ?压扁它?还是什么???
  • @Exlord 我也想打印或忽略它... .. 查看接受的答案
【解决方案2】:

只需使用array_walk_recursive

array_walk_recursive($decoded, function($key,$value) {
  echo $value.' :'.$key.'<br>';
});

输出

Title :The Cuckoos Calling
Author :Robert Galbraith
Publisher :Little Brown

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多