How to recover the value of an array

Asked

Viewed 336 times

3

Well I have the following array inside a variable $resultado:

{"result":[{"fone":"","email":"","id":1,"nome":"GERAL","token":"BE5DEA91EB28E98F053466E98082908545E3DCA5"}]}

I need to retrieve the token.

I tried that way, but it didn’t work:

$resultado[4]

But he’s returning me s

  • 1

    That’s a json, need a json_decode then yes access the desired key.

  • @Sergio made the following mistake Notice: Use of undefined constant result - assumed 'result' in C:\xampp\htdocs\Backup.php on line 44

Notice: Use of undefined constant token - assumed 'token' in C:\xampp\htdocs\Backup.php on line 44
{"result":[{"fone":"","email":"","id":1,"nome":"GERAL","token":"BE5DEA91EB28E98F053466E98082908545E3DCA5"}]}rtoken

2 answers

4


Utilize json_decode and then access the keys as follows:

<?php

$json = '{"result":
    [{"fone":"","email":"",
      "id":1,"nome":"GERAL",
      "token":"BE5DEA91EB28E98F053466E98082908545E3DCA5"}
    ]}';

$array = json_decode($json, true);

echo $array['result'][0]['token'];

Example: IDEONE

  • 2

    worked out, thanks.

1

Your string is shaped like JSON, first use the function json_decode to decode the string and convert to object, example:

<?php

$resultado = '{"result":[{"fone":"","email":"","id":1,"nome":"GERAL","token":"BE5DEA91EB28E98F053466E98082908545E3DCA5"}]}';
$resultado = json_decode($resultado);
//Pelo formato do json você pode ter mais de um result
foreach($resultado->result as $res){
    echo $res->token;
}

//Ou simplesmente
echo $resultado->result[0]->token;

IDEONE

Browser other questions tagged

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