We help IT Professionals succeed at work.

Arrays saved in mysql DB - how to extract properly in php

tjyoung
tjyoung asked
on
HI,
Within a mysql DB I have a column that contains vehicle extras. Typically looks like this:
["Extra1","Extra2","Extra3"]

Using php, how would I loop through these and echo out?

Tried this:
<?php $array =  explode(',', $vehicle->extras);

foreach ($array as $item) {
    echo "$item";
}

Open in new window


Problem is the quotes are being echo'd out as well and brackets ie:

["Turbo""TDI"]

Any help is appreciated.
Comment
Watch Question

Most Valuable Expert 2011
Top Expert 2016
Commented:
Not sure how they got into that string (maybe JSON) in the database column, but this should tease them out correctly.  Try using json_decode().  It will return a PHP array.
<?php 
$array =  json_decode($vehicle->extras);
var_dump($array);

Open in new window

Commented:
Ray has the right answer and deserves the points, but one note - add "true" as a second parameter to json_decode:

$array =  json_decode($vehicle->extras, true);

Otherwise you'll get an object back instead of an array.
you could just DELETE the un-needed text characters of " [ , and ]  with this

$rep = array("\"", "[", "]");
$vehicle->extras = str_replace($rep, "",  $vehicle->extras);

$array =  explode(',', $vehicle->extras);

Commented:
@Slick812 - Why do that when it's a valid JSON string?
Most Valuable Expert 2011
Top Expert 2016

Commented:
Manual manipulation of JSON-encoded data is a recipe for future catastrophe.  If any of the reserved characters are present in the data, they will be escaped to nullify their role as metacharacters.  Using str_replace() will remove them, leaving the escape characters intact, and changing the meaning of the variable.  So just do not do what is described in 41531003!