Json with Array within PHP array

Asked

Viewed 2,193 times

1

I run into a problem.

I have an API in URL passing

{
"id": "1",
"codeReferenceAdditional": "33B",
"isActive": true,
"personType": 1,
"profileType": 3,
"accessProfile": "Administradores",
"businessName": "Movidesk",
"corporateName": "Movimentti sistemas",
"cpfCnpj": "012345678900",
"userName": "admin",
"password": null,
"role": null,
"bossId": null,
"classification": null,
"createdDate": "2014-12-17T18:00:43.3339728",
"observations": "Cadastro realizado via api de pessoas.",
"addresses": [
  {
    "addressType": "Comercial",
    "country": "Brasil",
    "postalCode": "89035200",
    "state": "Santa Catarina",
    "district": "Vila Nova",
    "street": "Rua Joinville",
    "number": "209",
    "complement": "Sala 201",
    "reference": "Próximo a FURB",
    "isDefault": true
  }
],

I’m using the following structure in php to read the information

 $json = file_get_contents("https://api");



   $cliente = json_decode($json);


  echo "id: $cliente->id</br>"; 
  echo "nome: $cliente->corporateName</br>"; 
  echo "cpf/cnpj: $cliente->cpfCnpj </br> ";
  echo "Endereço: $cliente->addresses[0]->city";

but gives the following error in the browser

Notice: Array to string conversion in C:\xampp\htdocs\Maps\index.php on line 30
Endereço: Array[0]->city

I am unable to convert this second array.

  • echo "Endereço: $cliente->addresses{0}->city"; resolve? if you have no special reason to use an object I suggest an array even (in json return)

  • Not solved, but as I will read the second array?

  • For example, I’m a beginner in json

  • But you don’t even have the attribute city in the json of question O.o

  • has been changed from District to city; is that the api example is old

1 answer

2


The problem is using the array inside the string.

PHP is trying to convert $cliente->addresses for string and not the full expression $cliente->addresses[0]->city

Switch to any of the following modes and it should work:

echo "Endereço: " . $cliente->addresses[0]->city;

Or else:

echo "Endereço: {$cliente->addresses[0]->city} ";
  • 1

    Hello, milestones I used echo "Address: {$client->Addresses[0]->city} "; and it worked out! Thank you very much

  • 2

    @Jeanprado If the answer was useful to you you can mark it as correct using the V below the arrows to the left of the answer.

Browser other questions tagged

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