0

您好我正在使用函数 json_encode 通过关联数组从数据库中检索数据。但是我想问一下如何将 img 标签转换为字符串并将其放入关联数组中,然后让 json 对其进行编码并吐出所有内容,同时将 img 标签保持为字符串?

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

  $array = array(
  "adjacencies" => array( array(
  "nodeTo" => "$to",
  "nodeFrom" => "$id",
  "data" => array() )),
  "data" => array(
   "$"."color" => $color1,
   "$"."type" => $type1 ),
  "id" => $id,
  "name" => "<img src='$thumb' height='30' width='30' alt='root'/><label>$name</label> ");
}
$json = json_encode($array);
print "$json";
return $json;
4

3 回答 3

0

使用 htmlspecialchars 确保转义任何有问题的字符 ( http://php.net/manual/en/function.htmlspecialchars.php )。除此之外,在您将其插入 DOM 之前,它只是字符串数据。

我假设在循环的每次迭代中,您都打算向数组中添加另一个元素 $array。您想在循环之前初始化 $array 变量

$array = array()

而不是

$array = array(
...
)

在循环中,做

$array[$key] = array(
...
)

其中 $key 是您要用于索引数组的键。我假设您想为此使用 $id 。您也可以增加一个整数并使用它。

于 2013-03-14T05:10:55.523 回答
0

尝试这个:

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

    $array = array(
        "adjacencies" => array( array(
            "nodeTo" => "$to",
            "nodeFrom" => "$id",
            "data" => array() 
        )),
        "data" => array(
            "$"."color" => $color1,
            "$"."type" => $type1 ),
        "id" => $id,
        "name" =>htmlspecialchars("<img src='".$thumb."' height='30' width='30' alt='root'/><label>".$name."</label>")
    );
}
$json = json_encode($array);
echo $json;
return $json;

阅读http://php.net/manual/en/function.htmlspecialchars.php

于 2013-03-14T05:06:11.527 回答
0

首先,每次通过循环时都会覆盖 $array 。考虑修复以下行

...
$thumb =$row['thumb']; //image path

$array = array(
"adjacencies" => array( array(
"nodeTo" => "$to",
...

...
$thumb =$row['thumb']; //image path

$array[] = array(
"adjacencies" => array( array(
"nodeTo" => "$to",
...

除此之外,只是用一些默认变量尝试了你的代码

$id = $to = 1;
$color1 = 'green';
$type1 = 'type1';
$thumb = 'image.jpg';
$name = 'image name';
$array = array(
    "adjacencies" => array(
        array(
            "nodeTo" => $to,
            "nodeFrom" => $id,
            "data" => array()
        )
    ),
    "data" => array(
        "$"."color" => $color1,
        "$"."type" => $type1
    ),
    "id" => $id,
    "name" => "<img src='$thumb' height='30' width='30' alt='root'/><label>$name</label> "
);
echo json_encode($array);

将这个 JSON 返还给我,这似乎是您正在寻找的?

{
    "adjacencies": [
        {
            "nodeTo": 1,
            "nodeFrom": 1,
            "data": []
        }
    ],
    "data": {
        "$color": "green",
        "$type": "type1"
    },
    "id": 1,
    "name": "<img src='image.jpg' height='30' width='30' alt='root'/><label>image name</label> "
}
于 2013-03-14T05:08:49.000 回答