Traversing array of objects

Asked

Viewed 680 times

1

Good night.

I have an array of an object and would like to take two values:

object(OrgaosJurisdicionais)[17]
  protected 'data' => 
    array (size=3)
      'id' => string '3' (length=1)
      'nome' => string 'Tribunal de Justiça do Estado do Pernambuco' (length=44)
      'sigla' => string 'TJPE' (length=4)
  protected 'vdata' => null
  protected 'attributes' => 
    array (size=2)
      0 => string 'nome' (length=4)
      1 => string 'sigla' (length=5)

How do I only get the ID and NAME of this array?

I used the foreach below but did not return any value:

foreach ($unidades as $keys => $unidade)
        {
            echo $keys.' - '.$unidade->nome;
        }
  • You need the data in data, which is a field protected. Do you have any public method in class OrgaosJurisdicionais that allows you to access this value?

3 answers

7

I believe your variable unidades is an array of objects Orgaosjurisditional, this object has an attribute named data and is an array that contains the data id and nome, then to get the id value for example, you have to access the date attribute and then the id key.

<?php
foreach ($unidades as $keys => $unidade) {
    echo $unidade->data['id'] . ' - ' . $unidade->data['nome'];
}
  • 1

    Only problem is that data is a field protected of the object and you will not be able to access it so.

2

You can extract all values with array_map

$valores[] = array_map(function($obj) {
    return array($obj->data['id'], $obj->data['name']);
}, $unidades);
  • 1

    Only problem is that data is a field protected of the object and you will not be able to access it so.

  • Yes, I think you’ll need to call a method that returns this instead of directly accessing the attribute protected.

-1

I was able to resolve it simply with:

echo $unidade->id.' - '.$unidade->nome.'<br>';            

instead of

echo $keys.' - '.$unidade->nome;

being like this:

foreach ($unidades as $keys=>$unidade)
{
    echo $unidade->id.' - '.$unidade->nome.'<br>';
}
  • 1

    This is exactly the same code you put in the question and said it didn’t work. Why now it worked?

  • You’re right, Anderson. Looking here I found that I actually used the same function, but with a different criterion parameter. The problem was just in the fields protected, as you said, because this parameter does not have these fields protected. .

  • So I think both the question and the answer need more details. It seems to me that the real problem was omitted in both.

Browser other questions tagged

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