0

我需要从头开始创建一个 JSON 文件,看起来像这样

{
 "results": {
  "course": "CC167",
  "books": {
   "book": [
    {
      "-id": "585457",
      "-title": "Beginning XNA 20 game programming : from novice to professional",
      "-isbn": "1590599241",
      "-borrowedcount": "16"
    },
    {
      "-id": "325421",
      "-title": "Red Hat Linux 6",
      "-isbn": "0201354373",
      "-borrowedcount": "17"
    },
    {
      "-id": "424317",
      "-title": "Beginner's guide to darkBASIC game programming",
      "-isbn": "1592000096",
      "-borrowedcount": "46"
    },
    {
      "-id": "437390",
      "-title": "Objects first with Java : a practical introduction using BlueJ",
      "-isbn": "0131249339",
      "-borrowedcount": "89"
    },
    {
      "-id": "511094",
      "-title": "Objects first with Java : a practical introduction using BlueJ",
      "-isbn": "2006044765",
      "-borrowedcount": "169"
    }
   ]
  }
 }
}

这是我用来制作的 PHP,所以希望它不是一个大的飞跃,但我对如何从头开始在 PHP 中制作 JSON 对象一无所知,只有如何制作这样的东西,然后将其保存为JSON 自己

$y = 1;
    $json = "{";
    $json = $json . "\"results\": {";
    $json = $json . "\"course\": \"$cc\",";
    $json = $json . "\"books\": {";
    $json = $json . "\"book\": [";
    foreach ($my_array as $counter => $bc) {
        $json = $json . "{";
        $json = $json . "\"-id\": \"$id[$counter]\",";
        $json = $json . "\"-title\": \"$title[$counter]\",";
        $json = $json . "\"-isbn\": \"$isbn[$counter]\",";
        $json = $json . "\"-borrowedcount\": \"$borrowedcount[$counter]\"";
        $json = $json . "}";
        if ($x != $y) $json = $json .  ",";
        $json = $json . "";
        $y++;
    }
    $json = $json . "]";
    $json = $json . "}";
    $json = $json . "}";
    $json = $json . "}";
    echo $json;
4

2 回答 2

4

您可以使用json_encode从 PHP 中的数组生成 json

例如,这将生成类似于您上面的 json 的内容(稍微减少)

$data = array(
  "results" => array(
    "course" => "CC167",
    "books" => array(
      "book" =>
      array(
        array(
          "-id" => "585457",
          "-title" => "Beginning XNA 20 game programming : from novice to professional",
          "-isbn" => "1590599241",
          "-borrowedcount" => "16"
        ),
        array(
          "-id" => "325421",
          "-title" => "Red Hat Linux 6",
          "-isbn" => "0201354373",
          "-borrowedcount" => "17"
        )
      )
    )
  )
);
echo json_encode($data);

尝试通过手动字符串连接(如在您当前的代码中)生成 json 是个坏主意,因为它很难避免语法错误,并且您需要转义 json 的动态部分。json_encode 会自动为您转义。

于 2013-02-25T06:08:53.973 回答
0

尝试这个:

$array       = array("test"=>"value");

$json_string = json_encode($array);

参考: http: //php.net/manual/en/function.json-encode.php

于 2013-02-25T05:58:33.857 回答