Access array elements from JSON

2

I'm retrieving an object and turning this object into array .

Now, I need to access some elements of this array to populate this data in the controller (CodeIgniter), before returning it as JSON.

For the object below:

{
  "contratos":[

  ],
  "id":0,
  "id_operador":0,
  "pessoa_fisica":{
    "id":0,
    "rg":"",
    "dt_nascimento":"",
    "profissao":"",
    "salario":"",
    "genero":"1"
  },
  "pessoa_juridica":{
    "id":0,
    "nome_fantasia":"",
    "inscricao_estadual":""
  },
  "nome":"Wagner Carlos de Jesus Júnior",
  "cpf_cnpj":"096.686.256-25",
  "emails":[

  ],
  "enderecos":[

  ],
  "telefones":[

  ],
  "crud":null
}

I'm using the function json_decode and getting the following return with print_r

$objeto = $_POST['objeto'];

$objeto_decode = json_decode($objeto, true);
print_r($objeto_decode);

And the return is as below, however, I do not know how to access the element individually and fill it manually. For example, fill in the element [id_operador] with the session ID of the logged in user '

Array
(
    [contratos] => Array
        (
        )

    [id] => 0
    [id_operador] => 0
    [pessoa_fisica] => Array
        (
            [id] => 0
            [rg] => 
            [dt_nascimento] => 
            [profissao] => 
            [salario] => 
            [genero] => 1
        )

    [pessoa_juridica] => Array
        (
            [id] => 0
            [nome_fantasia] => 
            [inscricao_estadual] => 
        )

    [nome] => Wagner Carlos de Jesus Júnior
    [cpf_cnpj] => 096.686.256-25
    [emails] => Array
        (
        )

    [enderecos] => Array
        (
        )

    [telefones] => Array
        (
        )

    [crud] => 
)
    
asked by anonymous 15.08.2017 / 04:14

1 answer

2

Just refer to the array item. It would look like this:

$objeto_decode['id_operador'] = session_id();

Another example, to access the id of natural person:

$objeto_decode['pessoa_fisica']['id'] = 'Coloque a variável do ID aqui';

If you use:

// Isto
$objeto_decode = json_decode($objeto);
// Em vez disso
$objeto_decode = json_decode($objeto, true);

You can access the items as objects, it would look like this:

// Acesso ao objeto id_operador
$objeto_decode->id_operador = session_id();
// Acesso ao id da pessoa física
$objeto_decode->pessoa_fisica->id = 'Coloque a variável do ID aqui';

In particular, I prefer to use objects because they are better for reading. But this goes from each one, see which fits better and, well, programming.

    
15.08.2017 / 04:23