您好我正在使用函数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;
答案 0 :(得分: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;
答案 1 :(得分: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> "
}
答案 2 :(得分:0)
使用htmlspecialchars确保转义任何有问题的字符(http://php.net/manual/en/function.htmlspecialchars.php)。除此之外,它只是字符串数据,直到您将其插入DOM。
我假设在循环的每次迭代中,您打算在数组中添加另一个元素$ array。您想在循环
之前初始化$ array变量$array = array()
而不是
$array = array(
...
)
在循环中,执行
$array[$key] = array(
...
)
其中$ key是您要用来索引数组的键。我假设您想要使用$ id。你也可以增加一个整数并使用它。