Resume all values in stdClass Object Array

Asked

Viewed 6,197 times

2

I’d like some help. I have an Array that returns the following values:

Array
(
   [0] => stdClass Object
      (
         [seccionalid] => 1
         [seccionaldescricao] => DELSECPOL DE SJRIO PRETO
      )

   [1] => stdClass Object
      (
         [seccionalid] => 2
         [seccionaldescricao] => DELSECPOL DE JALES
      )

   [2] => stdClass Object
      (
         [seccionalid] => 3
         [seccionaldescricao] => DELSECPOL DE ARAÇATUBA
      )

I’m trying with echo or print_r, return to a function, all values of [seccionaldescricao] of Array, as follows:

$dados = $seccionais->fetchAll(PDO::FETCH_OBJ);
$dados2 = $dados[0]->seccionaldescricao;

print_r($dados2);

However, only one line is returned:

DELSECPOL DE SJRIOPRETO

How do I return all records?

4 answers

2

It seems that you need to create a new array only with this data. It can be manually, using a loop, as in André Baill’s answer, or using the function array_map, thus:

function descricoes($item) {
    return $item->seccionaldescricao;
}
$dados2 = array_map(descricoes, $dados);
print_r($dados2);
  • Thanks for the help bfavaretto;

  • The routine almost worked. Just returned this way: 2<br,> <b>Notice<,b>; Use of Undefined Constant descricoes - assumed 'descricoes' in <b>C: xampp htdocs Countdown classes...." Array ( [0] => DELSECPOL DE SJRIO PRETO [1] => DELSECPOL DE Jales [2] => DELSECPOL DE Araçatuba Just to clarify: I am trying to play these values inside a combobox. This combobox can be loaded, but with all the error message and all the items of the Array in one line (does not insert line-by-line); Thanks.

1

You can elaborate as follows:

$dados = $seccionais->fetchAll(PDO::FETCH_OBJ); 
foreach($dados as $valor){
    echo $valor->seccionaldescricao;
    echo "<br>";    
}

This way he will look for the arrays() you have assigned and will make the print according to the field you want.

  • 1

    I was able to do it through the suggestion of André Baill. The only point was in relation to item 0 of the Array that concatenated nr. 2 (two). It was like this in the combobox: 2DELSECPOL DE SJRIO PRETO DELSECPOL DE Jales DELSECPOL DE Araçatuba Could you tell me where this number came from. 2, since it is not in the database? Again, thank you.

  • Note: Only to clarify. The three items were loaded in separate (broken) lines. The only problem is with respect to nr. 2 concatenated.

  • Paste your SQL here... But it was not to come the number 2 together. Can paste a print of the result?

  • Place echo "<br><br><br>"; before the foreach and see if the 2 is concatenated @Vanderci

1

This is an array of objects, as an example I made the following entry from your collection:

<?php
$myCollection = [
    new stdClass(),
    new stdClass(),
    new stdClass(),
    ];

 //como no seu exemplo, você tem 3 posições do array que cada uma representa 2 atributos de um objeto stdClass 
    $myCollection[0]->seccionalid = 1;
    $myCollection[0]->seccionaldescricao = 'DELSECPOL DE SJRIO PRETO';

    $myCollection[1]->seccionalid = 2;
    $myCollection[1]->seccionaldescricao = 'DELSECPOL DE JALES';

    $myCollection[2]->seccionalid = 3;
    $myCollection[2]->seccionaldescricao = 'DELSECPOL DE ARAÇATUBA';

echo "<pre>";
print_r($myCollection);

class PHPIterator implements Iterator
    {
        private $collection = [];
        private $key        = 0;

        public function __construct(array $collection = [])
        {
            $this->collection = $collection;
        }

        public function rewind()
        {
            $this->key = 0;
        }

        public function current()
        {
            return $this->collection[$this->key];
        }

        public function key()
        {
            return $this->key;
        }

        public function next()
        {
            ++$this->key;
        }

        public function valid()
        {
            return isset($this->collection[$this->key]);
        }
    }

    //aqui você faz a interação:
    $phpIterator = new PHPIterator($myCollection);

    //abaixo eu faço com três casos de interação
    echo "-----------------while--------------------\n";

     $phpIterator->rewind();

    while ($phpIterator->valid()) {

        echo $phpIterator->current()->seccionalid."\n";
        echo $phpIterator->current()->seccionaldescricao."\n";
        $phpIterator->next();
    }

    echo "-------------------for--------------------\n";


    for ($phpIterator->rewind(); $phpIterator->valid(); $phpIterator->next()) {
        echo $phpIterator->current()->seccionalid."\n";
        echo $phpIterator->current()->seccionaldescricao."\n";
    }


    echo "------------------foreach-----------------\n";

    foreach ($phpIterator as $key => $object) {
       echo $object->seccionalid."\n";
       echo $object->seccionaldescricao."\n";
    }

The PHP documentation has more information about this Pattern design: http://php.net/manual/en/class.iterator.php

Now using a more basic, non-Pattern design, you can do it this way:

    //Suponha que sua coleção seja essa:
            $myCollection = [
            new stdClass(),
            new stdClass(),
            new stdClass(),
            ];

         //como no seu exemplo, você tem 3 posições do array que cada uma representa 2 atributos de um objeto stdClass 
            $myCollection[0]->seccionalid = 1;
            $myCollection[0]->seccionaldescricao = 'DELSECPOL DE SJRIO PRETO';

            $myCollection[1]->seccionalid = 2;
            $myCollection[1]->seccionaldescricao = 'DELSECPOL DE JALES';

            $myCollection[2]->seccionalid = 3;
            $myCollection[2]->seccionaldescricao = 'DELSECPOL DE ARAÇATUBA';
//lembrando que a variável $myCollection é uma simples representação do retorno de: $dados = $seccionais->fetchAll(PDO::FETCH_OBJ);

if (count($myCollection)) {
    foreach($myCollection as $data) {
       echo $data->seccionalid.'<br>';
       echo $data->seccionaldescricao.'<br>';
    }
}

Here the working example: http://viper-7.com/IXwoVj

  • One of the things that many people confuse is that when the array has no indexes or defined keys(a)s, these indexes become 0, 1, 2, 3... and each index represents an element of the array. Arrays can be defined by [] or by array(), and these keys can receive values that are assigned by =>

1

When you access -> is referencing an attribute with 1 item, to access all, you will need to create a loop:

foreach($seccionais as $result){
    echo($result->seccionaldescricao);
}

or

while ($row = $seccionais->fetch(PDO::FETCH_ASSOC))
{
$seccionaldescricao= $row['seccionaldescricao'];
}

Browser other questions tagged

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