Skip to content
Advertisement

mysql JSON_EXTRACT in PHP returning “Array” instead of indexed element’s value

Very basic thing I’m probably missing, but I don’t get it. I have a table called mus_translated_languages in my db, in which I have a json datatype column (six records), whose value is always in the structure of:

["GERMAN","ENGLISH","FRENCH"]

When I use the following code:

$sql = 'SELECT labels->"$[1]" FROM mus_translated_languages';
$result = mysqli_query( $conn, $sql );
if ( mysqli_num_rows( $result ) > 0 ) {
  while ( $row = mysqli_fetch_assoc( $result ) ) {
    echo $row;
  }
}

Instead of getting the six corresponding languages, I get the following output:

ArrayArrayArrayArrayArrayArray

So it looks like my code can’t read the output value, but only its data type. What am I missing??

UPDATE

I used var_dump($row) instead of echo $row in the code above to see what we have, and the server returned:

array(1) { ["labels->"$[1]""]=> string(9) ""Deutsch"" } array(1) { ["labels->"$[1]""]=> string(10) ""Englisch"" }

and so on and so fourth, for the 6 arrays / records. I then used:

foreach ($row as $key => $value) {
      echo $value;
    }

instead of echo $row in the code above, and got what I wanted. I however feel that this is not the way it’s supposed to be; PHP retrieves the single array elements as one-indexed subarrays, instead of retrieving them as values.. What am I missing?

Advertisement

Answer

Alright, so when I used an alias for the name of the output column of my query result, and unquoted the string resulting from the query by using ->> instead of -> it worked, like so:

$sql = 'SELECT labels->>"$[2]" AS label FROM mus_translated_languages';
$result = mysqli_query( $conn, $sql );
if ( mysqli_num_rows( $result ) > 0 ) {
  while ( $row = mysqli_fetch_assoc( $result ) ) {
    echo $row['label'];
  }
}

P.S. : I was originally planning to query for array elements using variable array indexes. Thanks to this post https://medium.com/aubergine-solutions/working-with-mysql-json-data-type-with-prepared-statements-using-it-in-go-and-resolving-the-15ef14974c48, I was able to figure out how to do that, so I thought this post may also help others with similar concerns / ideas.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement