Access object inside object (Sdtclass - Codeigniter)

Asked

Viewed 1,434 times

3

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

And in 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;

Turns out I’m only getting access to 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 tried it this way and I couldn’t:
$objeto_decode->contratos->negociacoes;

Json

json

Object

objeto

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 attribute contratos, just do $objeto_decode->contratos. However, the type of contract attribute is array, then we must inform the key that indicates which position we desire. 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 every element of that array is an object that has the attribute negociacoes, then, to access this attribute:

$objeto_decode->contratos[0]->negociacoes

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

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

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

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

As requested in the comments, to go through all contracts, negotiations and installments, a loop of repetition would be required for each. See 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

        }

    }

}
  • only one doubt. Using foreach I can use as shown in the image: https://uploaddeimagens.com.br/images/001/080/original/erro.png?1504884435

  • I’m getting this mistake: Message: Trying to get property of non-object no model. In this line: 'id' => $ctt->id,

  • Your function does not make much sense, tries to review what you have done and understand the problem.

Browser other questions tagged

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