简体   繁体   English

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

[英]How do I remove some of the square brackets that wrap a JSON array

I am trying to workout how to format the brackets that are wrapping my JSON array. 我正在尝试锻炼如何格式化包裹我的JSON数组的括号。 I am pulling the data for my array out of my database using this code. 我正在使用此代码从数据库中提取阵列数据。

 $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]);
  }

Once converted to JSON the Array prints to the screen in this format. 转换为JSON后,数组将以这种格式打印到屏幕上。 I need the first square brackets to remain but need to swap the second set of brackets for (\\'). 我需要保留第一个方括号,但需要将第二组方括号替换为(\\')。

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"],
];

So the Array should look more like this. 因此,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"],
 ];

The reason I need the Array in this format is so that I can pass the data into Google Maps function which expects the Array to have 4 columns. 我需要这种格式的Array的原因是为了可以将数据传递到Google Maps函数中,该函数希望Array具有4列。

I have worked out I can remove the brackets with a function like this, but the problem is it removes all the brackets and I need the external brackets; 我已经计算出可以使用类似的功能移除支架,但是问题是它移除了所有支架,并且我需要外部支架。

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

How would I keep the external brackets and simply remove the internal brackets? 我如何保留外部支架并简单地卸下内部支架? If I have not given enough information or I should add any more details let me know. 如果我没有提供足够的信息,或者我应该添加更多详细信息,请告诉我。

Thanks 谢谢

How about making your array the way you need it in the first place? 首先如何按照需要的方式制作数组? Instead of: 代替:

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

Do this: 做这个:

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

try 尝试

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

and if the brackets are also double on the end (not in your example) 以及如果括号在末尾也加倍(不在您的示例中)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM