Convert a string from an array to an array type in PHP


In short, I have something like this:

$variable = "[{"id":1, "nombre":"Juan"},{"id":2, "nombre":"Manuel"}]"

As you can see, it's a string and I want to pass it to an array, the goal is to be something like:

$variable = [
    ['id' => 1, 'nombre'=>'Juan']
    ['id' => 2, 'nombre'=>'Manuel']

I have researched, but I do not get the way to make it work.

asked by Franklin'j Gil'z 24.06.2018 в 23:22

2 answers


The chain you present is actually considered a JSON. Therefore, there is a proper function to convert a JSON to an array: that function is json_decode .

But it would be necessary that the variable begin and end with single quotes, and that you pass a second parameter TRUE to create an array from $variable , which, as we have said, is not more than a json.

Let's see:

/*Creamos la variable empezando y terminado con '*/
$variable = '[{"id":1, "nombre":"Juan"},{"id":2, "nombre":"Manuel"}]';

/*Pasamos la variable y TRUE a json_decode*/

/*Probamos nuestro array*/


    [0] => Array
            [id] => 1
            [nombre] => Juan

    [1] => Array
            [id] => 2
            [nombre] => Manuel


Also, we can run it from code to present its values:

foreach ($arr as $row){
    echo "id: ".$row["id"]." - nombre: ".$row["nombre"].PHP_EOL;


id: 1 - nombre: Juan
id: 2 - nombre: Manuel
answered by 25.06.2018 / 01:02

I tell you the following you can use the PHP function explode and tell you what element you will find to make the separation

I also think that you are using quotation marks incorrectly, because if you use double quotes for all statements then the key and value elements will try to read them as variables, which will cause an error; it should look like this

$variable = "[{'id':1, 'nombre':'Juan'},{'id':2, 'nombre':'Manuel'}]";
$arreglo = explode(',', $variable);

Use var_dump () to show you the lontitude and types of   data that are contained in the variable $ arrangement

answered by 24.06.2018 в 23:35