【问题标题】:json encoding from array issue来自数组问题的 json 编码
【发布时间】:2013-03-12 09:02:33
【问题描述】:

您好,我正在尝试对关联数组进行 json_code 编码,最终结果应如下面的 json 数组所示

   var json =[{  "adjacencies": [
      {
        "nodeTo": "graphnode9",
        "nodeFrom": "graphnode5",
        "data": {}
      }
    ],
    "data": {
      "$color": "#C74243",
      "$type": "triangle"
    },
    "id": "graphnode5",
    "name": "graphnode5"
  }];

这是我尝试将关联数组放入 json_encode 但它似乎不起作用,您可能会看到任何错误吗?非常感谢

   function getjson(){  
   $db = adodbConnect();
   $query = "SELECT nodes.*, relationships.* FROM nodes inner JOIN relationships ON nodes.id = relationships.id";
  $result = $db -> Execute($query);

  while($row=$result->FetchRow())
   {
  $id= (float)$row['id'];
  $name = $row['name'];
  $color1 = $row['color'];
  $type1 = $row['type'];
  $to= (float)$row['to'];

  $array = array(
  "adjacencies:" => array(
  "nodeTo" => "$to",
  "nodeFrom" => "$id",
  "data" => array() ),
  "data" => array(
   "$"."color" => $color1,
   "$"."type" => $type1 ),
  "id".":" => $id,
  "name".":" => $name);

}
print"$array";
json_encode($array);
}

【问题讨论】:

  • 你得到了什么结果?
  • 您不会对json_encode 执行任何操作,它会返回一个您必须使用的结果。另外,您没有正确使用print数组,请使用print_r
  • 是我生成的数组与我希望的 json 数组的语法相同吗?我很迷失在那部分。我不能完全指望它
  • 这是我的数组 Array ( [adjacencies:] => Array ( [nodeTo] => 2 [nodeFrom] => 1 [data] => Array ( ) ) [data] = > 数组 ( [$color] => #83548B [$type] => circle ) [id:] => 1 [name:] => Blue Jay)

标签: php javascript mysql json


【解决方案1】:

您希望创建的数组看起来像:

$array = array(
  "adjacencies" => array(
      "nodeTo" => "$to",
      "nodeFrom" => "$id",
      "data" => array()
  ),
  "data" => array(
       '$color' => $color1,
       '$type' => $type1
  ),
  'id' => $id,
  'name' => $name
);

这将给出json_encode 的一个结果,从那里开始,这取决于您如何循环以将所有数据返回到您的应用程序。不过,您确实需要将json_encode 分配给$my_json = json_encode($array); 之类的东西

【讨论】:

  • Array ( [adjacencies:] => Array ( [nodeTo] => 2 [nodeFrom] => 1 [data] => Array ( ) ) [data] => Array ( [$color] => #83548B [$type] => circle ) [id:] => 1 [name:] => Blue Jay ) 这是我使用 print_r 得到的结果,但是任何地方都没有逗号
  • 这不是我输入的代码的结果。另外,没有逗号,因为你在上面使用了json_encode,用<pre>标签回显以查看它的格式...
  • 在将其编码为 json 时,逗号是否重要?
  • 没有。你以前没用过 PHP arrays 吗?
  • 是的,我有,但是我没有对其进行编码,我只是 print_r,我得到的输出是这样的,我把编码拿出来了。 Array ( [adjacencies:] => Array ( [nodeTo] => 2 [nodeFrom] => 1 [data] => Array ( ) ) [data] => Array ( [$color] => #83548B [$type] => circle ) [id:] => 1 [name:] => Blue Jay )
猜你喜欢
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 2016-09-04
  • 1970-01-01
相关资源
最近更新 更多