简体   繁体   中英

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. 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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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