how to handle JSON Array in PHP

Asked

Viewed 94 times

1

I’m having difficulty dealing with this Array not being able to hit the paths in PHP.

Below I list the Array

{
  "Result": [
    {
      "MatchKeys": "doc{57279000000}",
      "CreditData": [
        {
          "Origin": "DATABANCO",
          "QueryDate": "2019-02-21T00:00:00",
          "BasicData": {
            "TaxIdNumber": "57279000000",
            "TaxIdCountry": "Brazil",
            "AlternativeIdNumbers": {
              "VoterRegistration": "6521890442"
            },
            "Name": "JANAIR DOS ",
            "Gender": "U",
            "BirthDate": "1967-11-30T00:00:00",
            "Age": 51,
            "ZodiacSign": "SAGITARIO",
            "MotherName": "MARIA TERES ",
            "TaxIdStatus": "",
            "TaxIdOrigin": "DATABANCO"
          },
          "PersonalRelationships": [
            {
              "RelatedEntityName": "MARIA TERES",
              "RelationshipType": "MOTHER",
              "RelationshipLevel": "DIRECT"
            }
          ],
          "Emails": [],
          "Phones": [],
          "Addresses": [
            {
              "AddressMain": "R MONTEIO LOBATO",
              "Number": "005477",
              "Complement": "",
              "Neighborhood": "",
              "ZipCode": "95780000",
              "City": "MONTENEGRO",
              "State": "RS",
              "Country": "Brazil"
            }
          ],
          "TotalDebts": 9217.06,
          "TotalCount": 1,
          "TotalPreviousQueries": 2,
          "PreviousQueries": [
            {
              "Origin": "SPC BRASIL - SAO PAULO / SP",
              "QueryDate": "2019-02-21T00:00:00",
              "Name": "BIG DATA SOLUCOES EM TECNOLOGIA",
              "CityAndState": {
                "City": "RIO DE JANEIRO",
                "State": "RJ"
              }
            },
            {
              "Origin": "DATABANCO BRASIL - SAO PAULO / SP",
              "QueryDate": "2019-02-16T00:00:00",
              "Name": "BIG DATA SOLUCOES EM TECNOLOGIA",
              "CityAndState": {
                "City": "RIO DE JANEIRO",
                "State": "RJ"
              }
            }
          ],
          "Occurrences": [
            {
              "Name": "PROTEST",
              "TotalValue": 9217.06,
              "TotalCount": 1,
              "FirstOccurrenceDate": "0001-01-01T00:00:00",
              "LastOccurrenceDate": "2019-01-09T00:00:00",
              "AdditionalOutputData": {},
              "Details": [
                {
                  "Origin": "",
                  "ExpiringDate": "0001-01-01T00:00:00",
                  "Date": "2019-01-09T00:00:00",
                  "Reason": "",
                  "Value": 9217.06,
                  "Count": 1,
                  "IssuingPeople": [],
                  "IssuingCompanies": [
                    {
                      "TaxIdNumber": "",
                      "OfficialName": "UN",
                      "TradeName": "",
                      "Phones": [],
                      "Addresses": [
                        {
                          "AddressMain": "",
                          "Number": "",
                          "Complement": "",
                          "Neighborhood": "",
                          "ZipCode": "",
                          "City": "MONTENEGRO",
                          "State": "RS",
                          "Country": "Brazil"
                        }
                      ],
                      "AdditionalOutputData": {
                        "Contract": ""
                      }
                    }
                  ],
                  "AdditionalOutputData": {}
                }
              ]
            }
          ],
          "Score": {
            "Name": "SCORE 12 MONTHS",
            "Class": "F",
            "Horizon": "12",
            "Probability": "0",
            "Score": "0",
            "ScoreType": "RESTRICTED",
            "Reason": "O DOCUMENTO CONSULTADO APRESENTA REGISTRO(S) DE INADIMPLENCIA.",
            "AdditionalOutputData": {}
          }
        }
      ]
    }
  ],
  "QueryId": "dcff3486-2327-4628-5468-dsfdsf4654fds",
  "ElapsedMilliseconds": 3277,
  "Status": {
    "ondemand_credit_score_12_months": [
      {
        "Code": 0,
        "Message": "OK"
      }
    ]
  }
}

And below the return.php, however I am not able to integrate the path correctly in order to load the data stored in the Array...

<?php
//a opção true vai forçar o retorno da função como array associativo.
$conteudo = json_decode(file_get_contents('resultado.json'), true);

foreach($conteudo as $chave => $registro)
$Data = $registro->CreditData;
{
        $Origin = isset($registro['BasicData']) ? $registro['BasicData'] : [];
        $PersonalRelationships = isset($registro['PersonalRelationships']) ? $registro['PersonalRelationships'] : [];
        $IssuingCompanies = isset($registro['IssuingCompanies']) ? $registro['IssuingCompanies'] : [];
        $Addresses = isset($registro['IssuingCompanies']['Addresses']) ? $registro['IssuingCompanies']['Addresses'] : [];


        /*******************Exibição generica*******************************/
        exibir('BasicData', $Origin);
        exibir('PersonalRelationships', $PersonalRelationships);
        exibir('IssuingCompanies', $IssuingCompanies);
        exibir('Addresses', $Addresses);
}

function exibir($titulo, $registro){
    echo '<br><br>' . $titulo;
    foreach($registro as $chave => $registro){
        if(is_array($registro)){
            foreach($registro as $chave => $valor){
                echo '<br>' . $chave . ' : ' . $valor;
            }
        }else{
            echo '<br>' . $chave . ' : ' . $registro;
        }
    }
}

I mean... I think I’m missing the "way" ...

The idea here is that when it loads the data located in "Addresses" and shows everything below it:

          "AddressMain": "R MONTEIO LOBATO",
          "Number": "000107",
          "Complement": "",
          "Neighborhood": "",
          "ZipCode": "95780000",
          "City": "MONTENEGRO",
          "State": "RS",
          "Country": "Brazil"

I mean... the animal is picking up on this blessed path... If anyone can help me I’m grateful

2 answers

0

Your Result is an array of several objects, your need to start in the Results.

And the CreditData is also an array, and Addresses is also an array, so you will need more foreachs

It would be something like

foreach($conteudo->Result as $chave => $registro){
    $Data = $registro->CreditData;
    foreach($Data->Addresses as $Addresses){
        foreach($Addresses as $Addr){
            //aqui voce via pegar cada item do endereco
            echo $Addr->AddressMain;
            echo $Addr->Number;
            echo $Addr->Neighborhood;
            echo $Addr->ZipCode;
            //......
        }
    }
    //....
  • Neuber Oliveira, not abusing ... but how do I integrate this example in php above ( return.php)? I tried but still giving error...

0

As you yourself put in your code commentary //a opção true vai forçar o retorno da função como array associativo.

//a opção true vai forçar o retorno da função como array associativo.
$conteudo = json_decode(file_get_contents('resultado.json'), true);

Knowing this you will not be able to access this element this way

$Data = $registro->CreditData;

You have to access the element like this:

$Data = $registro['CreditData'];

Another thing is that looking at your json the die begins like this

{
  "Result": [  <- Array de objetos
    {  
      "MatchKeys": "doc{57279000000}",
      "CreditData": [  <- Array de objetos
        {
          "Origin": "DATABANCO",

then to access the CreditData it would have to be something like

$conteudo['Result'][0]['CreditData']
             ^      ^
             |      Indice do objeto você quer
             |
             Seu foreach esta rodando aki, 
             se voce der um print na $chave vai aparecer 'Result'
             ou seja $registro == $conteudo['Result']                 

if you want to access the data Origin it would have to be something like

$conteudo['Result'][0]['CreditData'][0]['Origin']
                                     ^
                                     Indice do objeto que você quer

then you have to review your interaction, think what Voce wants and something like

//                   Note que o foreach esta no 'Result'
//                   ^             
foreach($conteudo['Result'] as $chave => $registro)
{
    $Data = $registro['CreditData'];
    $Data[0]['BasicData'] 
    //    ^ 
    //    talvez precise interar aqui tambem

}
  • 1

    Icaro, I understand your explanation.... however I tried to integrate in the model that I have "return.php" that this above, but I can not always returns me error, I’ve changed so much that I don’t even know what else to do... :((

  • The best now and you do by steps, first step corrects the foreach after that, start picking from one to one, ex. I want the Addresses There you look your json and think I think Addresses is in $Data[0]['Addresses'] then you take this variable and try to give print_r or var_dump That way you’ll see if it’s the expected die. If it’s the expected data you pass to the next variable you need, don’t try to do it all at once, I think that’s what’s making you curl up.

Browser other questions tagged

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