4

I would like to format the echo json_encode, the output is currently

{"results":{"course":"CC140","books":{"book":[[{"id":"300862","title":"Building object-oriented software","isbn":"0070431965","borrowedcount":"6"}]]}}}

Whereas i would like to to output like this:

{
    "results": {
        "course": "CC140",
        "books": {
            "book": [
                [
                    {
                        "id": "300862",
                        "title": "Building object-oriented software",
                        "isbn": "0070431965",
                        "borrowedcount": "6"
                    }
                ]
            ]
        }
    }
}

This is the code that makes the JSON

$temp = array();
    foreach ($my_array as $counter => $bc) {
        $temp['id'] = "$id[$counter]";
        $temp['title'] = "$title[$counter]";
        $temp['isbn'] = "$isbn[$counter]";
        $temp['borrowedcount'] = "$borrowedcount[$counter]";
        $t2[] = $temp;
    }

        $data = array(
  "results" => array(
    "course" => "$cc",
    "books" => array(
      "book" =>
      array(  
        $t2
      )
    )
  )
);
    echo json_encode($data);

Any help or pointers would be appreciated, thanks

Adding this

header('Content-type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);

formats the JSON, but the header also outs the entire HTML document

4

2 に答える 2

19

私が与える最初のアドバイスは次のとおりです。JSONはデータ形式です。サーバーにフォーマットさせるのではなく、ツールを使用して対処します。

それを無視する場合は、json_encode関数のマニュアルを参照してください。この関数には、返されたデータで空白を使用してフォーマットするために説明されているオプションのリストが含まれています。PHP5.4.0以降で使用できます。JSON_PRETTY_PRINT

したがって、手順は次のとおりです。

  1. PHP5.4.0以降を使用していることを確認してください
  2. json_encode($data, JSON_PRETTY_PRINT);
于 2013-02-25T12:31:31.357 に答える
4

json_encode($data, JSON_PRETTY_PRINT)php5.4以降で使用できます

php 5.3以下では、正規表現でフォーマットしてみることができますが、安全ではありません(または、ライブラリを使用してjsonをエンコードすることもできます)。

于 2013-02-25T12:31:30.907 に答える