如何删除一些包装JSON数组的方括号

时间:2013-08-28 15:02:54

标签: php arrays json

我正在尝试研究如何格式化包装我的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"],
];

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

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));

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

由于

2 个答案:

答案 0 :(得分: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]
);

答案 1 :(得分:2)

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

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

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