PHP take value from a multidimensional array

Asked

Viewed 1,324 times

0

 $arquivo = '{"nome":"João","cpf":"00000","teste":"ooooo"}';
 $dd = json_decode($arquivo, TRUE);

foreach($dd as $value)
{
$nome = $value->{'nome'};
$cpf = $value->{'cpf'};

}

I want to take the name value and Cpf of the array but the result comes null for the variables, anyone knows how to solve? please

  • This seems more like a syntax error.

  • I write echo $value; here comes "John" as if it only had that value there

1 answer

4


When you use the json_decode function, it converts the json data into an associative array, so you can use the foreach calling element of an array using an index and not attributes of an object. For example:

<?php
$arquivo = '[{"nome":"João","cpf":"00000","teste":"ooooo"},{"nome":"João 2","cpf":"000002","teste":"ooooo2"}]';
$dd = json_decode($arquivo, TRUE);
foreach($dd as $value){
    echo $value['nome'].'<br/>';
    echo $value['cpf'].'<br/>';
    echo $value['teste'].'<br/>';
}
?>

In the example I added one more json element, so that there are two records to help you understand. I hope I’ve helped.

  • Thanks for the help!

Browser other questions tagged

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