0

所以这是我在 PHP 中的原始数组

$data = array(
  "results" => array(
    "course" => "$cc",
    "books" => array(
      "book" =>
      array(  
      //Place temp here;  
      )
    )
  )
);

这是我在数组中间有更多数据要走的地方,可能是数百个,甚至可能只有一个

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

所以它可以用有效的 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"
    }
   ]
  }
 }
}

感谢您提供的任何帮助

4

1 回答 1

3

循环并添加所有值后,将book数组元素分配给值。$temp

$data['results']['books'] = $temp;

或者,首先循环,当$data您已经拥有所需的值时设置数组:

$data = array("results" => array("course" => "$cc", "books" => $temp));
于 2013-02-25T12:04:31.790 回答