We help IT Professionals succeed at work.

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

tjyoung asked
Within a mysql DB I have a column that contains vehicle extras. Typically looks like this:

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:


Any help is appreciated.
Watch Question

Most Valuable Expert 2011
Top Expert 2016
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.
$array =  json_decode($vehicle->extras);

Open in new window

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

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

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!