1

我正在尝试锻炼如何格式化包装我的 JSON 数组的括号。我正在使用此代码将我的数组的数据从我的数据库中提取出来。

 $result = mysqli_query($con,"SELECT * FROM table");
 $column = array();
  while ($row = mysqli_fetch_array($result))
  {
   $column[] = array(array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5]),$row[3],$row[2],$row[0]);
  }

一旦转换为 JSON,Array 就会以这种格式打印到屏幕上。我需要保留第一个方括号,但需要将第二组括号交换为 (\')。

var myVar = [
[["22","mike"," 151.1272","-33.9324","learning to fish","08\/14\/13"],"-33.93024"," 151.12896172","22"],
[["23","mike"," -2.09875","51.44501","learning french","08\/04\/13"],"51.44501"," -2.09775","23"],
[["24","mike"," -2.16375","51.44823019014051","Programming","08\/05\/13"],"51.451"," -2.1675","24"],
];

所以数组应该看起来更像这样。

var myVar = [
['"22","mike"," 151.12","-33.934","learning to fish","08\/14\/13"',"-33.94"," 151.12","22"],
['"23","mike"," -2.095","51.41","learning french","08\/04\/13"',"51.41"," -2.095","23"],
['"24","mike"," -2.165","51.41","Programming","08\/05\/13"',"51.44851"," -2.1675","24"],
 ];

我需要这种格式的数组的原因是我可以将数据传递到谷歌地图函数中,该函数期望数组有 4 列。

我已经弄清楚我可以使用这样的功能删除括号,但问题是它删除了所有括号,我需要外部括号;

$js_array = str_replace(array('[', ']'), '\'', htmlspecialchars(json_encode($column), ENT_NOQUOTES));

我将如何保留外部支架并简单地移除内部支架?如果我没有提供足够的信息或者我应该添加更多详细信息,请告诉我。

谢谢

4

2 回答 2

3

首先按照您需要的方式制作阵列怎么样?代替:

$column[] = array(
    array(
        $row[0],
        $row[1],
        $row[2],
        $row[3],
        $row[4],
        $row[5]
    ),
    $row[3],
    $row[2],
    $row[0]
);

做这个:

$column[] = array(
    $row[0] . $row[1] . $row[2] . $row[3] . $row[4] . $row[5],
    $row[3],
    $row[2],
    $row[0]
);
于 2013-08-28T15:07:34.900 回答
2

尝试

str_replace('[["','[\'"',$string);

如果括号最后也是双倍的(不在你的例子中)

str_replace('"]]','"\']',$string);
于 2013-08-28T15:10:08.987 回答