Access object within object (SdtClass - Codeigniter)

3

Hello! Through ajax data: { 'objeto': JSON.stringify(_obj_devedor) } ; I am sending the following objeto to the server.

And in the codeigniter, I'm converting as follows:
$objeto = $_POST['objeto']; $objeto_decode = json_decode($objeto);

And accessing the items (example: contracts) as follows:. $objeto_decode->contratos;

I can only access this item. So how can I access items that are nested to contratos , as highlighted in red in the image below, in negociacoes and parcelas ?

I've already tried the following way and I could not:
$objeto_decode->contratos->negociacoes;

Json

Object

    
asked by anonymous 08.09.2017 / 14:32

1 answer

3

Just look at the types of each value. That is, the return of:

$objeto_decode = json_decode($objeto);

It will be an object, so to access the contratos attribute, just do $objeto_decode->contratos . However, the type of the contracts attribute is array , so we must enter the key that indicates which position we want. If it is the first, just enter the value 0 - if they are all, just go through a loop:

$objeto_decode->contratos[0] // Retorna o primeiro elemento de contratos

But each element of this array is an object that has the negociacoes attribute, so to access this attribute:

$objeto_decode->contratos[0]->negociacoes

Again, negociacoes is a array of objects that have the parcelas attribute, then we must enter the key that indicates the position we want:

$objeto_decode->contratos[0]->negociacoes[0]->parcelas

Finally, parcelas will also be array of objects, so, for example, if you need the value of the first installment, the first deal, the first contract, would be:

echo $objeto_decode->contratos[0]->negociacoes[0]->parcelas[0]->valor;

As requested in the comments, to loop through all contracts, negotiations, and installments, you would need a loopback for each. Here's an example below:

// Percorre todos os contratos:
foreach ($objeto_decode->contratos as $contrato) {

    // Percorre todas as negociações:
    foreach ($contrato->negociacoes as $negociacao) {

        // Percorre todas as parcelas:
        foreach ($negociacao->parcelas as $parcela) {

            // Código

        }

    }

}
    
08.09.2017 / 15:18