Javascript 获取字符串格式的MySQL存储数组,并转换为JSON对象中的数组
我在mysql表中存储了一个数组,如下所示:Javascript 获取字符串格式的MySQL存储数组,并转换为JSON对象中的数组,javascript,php,mysql,arrays,json,Javascript,Php,Mysql,Arrays,Json,我在mysql表中存储了一个数组,如下所示: [3,5,6,7,8] $results = array( array( "id" => 43, "incidence" => "[0,3,6,7]" ) ); foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference) $no_brackets = trim
[3,5,6,7,8]
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
当我选择它时,在PHP中将其编码为JSON,然后将其解析为javascript对象,而不是将其变成数组,它只是变成字符串“[3,5,6,7,8]”。我知道不可能将其存储为单个字段中的数组,因此。。我该怎么做才能使它正确地转换为数组而不是字符串
我当前的代码:
test = JSON.parse('[{"id":43,"incidence":"[0,3,6,7]"}]')
我可以解决删除字符串上的“字符串”的问题,但mysql会用字符串返回它,php用引号编码,javascript用引号解析。因此,基本上,在这个过程中有没有办法删除它?您需要做一些修改才能使其正常工作 试试这个
<?php
$string = '[3,5,6,7,8]';
$t = str_replace(array('[',']'), '', $string);
$array = explode(',', $t);
echo json_encode($array);
问题在于如何在将数组转换为JSON之前构造数组。由于您是从数据库中检索这些结果,因此我假设您正在构造一个多维数组,其外观可能如下所示:
[3,5,6,7,8]
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
因为关联
是一个字符串,所以在JS中使用它时会出现这些错误。要解决这些问题,您需要将该字符串转换为数组。现在,由于您可能有多个结果(因为这些是数据库结果),您需要迭代结果数组并将该字符串转换为如下数组:
[3,5,6,7,8]
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
希望这能有所帮助。您能展示您的代码吗?您是如何编码它的?您是如何解析它的?在初始解析之后,您是否尝试过这样做:
JSON.parse(test[0].incident)
?在您的数据库结果中,您总是只有一行结果吗?或者有时会有多行结果吗?我这样问是因为目前您有一个数组数组,这使得以后需要进行额外的迭代。