Transforming elements from a string into a PHP array

Asked

Viewed 470 times

-2

mysql returns the following string: ["Element1", "Element2", "Element3", "Element4", "Element5", "Element6"]

I need to transform each of the words between "" into an element of an array. I tried from the preg_split and preg_match_all functions but could not get the correct regular expression.

  • If it’s a JSON, why don’t you try json_decode?

  • @Andersoncarloswoss because JSON_EXTRACT is a function executed in mysql query that brings only the desired JSON information without having to go through it in PHP

  • But he converts his string in the array which you need, if I understand correctly what you want to do.

  • @Andersoncarloswoss transforms the result into a string. I need to transform what is between " " into components of an array.

  • Look at my answer. It seems you don’t quite understand how json_decode works; but if it is not what I answered, I ask you to edit the question and clarify better what you need to do, because the way you are making it seem that it is enough to use this function, because it generates the array with all the strings.

1 answer

0


If the return of your SQL is the string:

$str = '["Elemento1", "Elemento2", "Elemento3", "Elemento4", "Elemento5", "Elemento6"]';

Then just use the function json_decode to generate the array:

$arr = json_decode($str);

The array will be generated:

array (
  0 => 'Elemento1',
  1 => 'Elemento2',
  2 => 'Elemento3',
  3 => 'Elemento4',
  4 => 'Elemento5',
  5 => 'Elemento6',
)

See working on Ideone

  • It worked! I didn’t know that the json_decode function also converted strings

  • The following manual: http://php.net/manual/en/function.json-decode.php

  • @Romulosousa the documentation is already linked in the answer xD

  • It was bad haha, I didn’t get it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.