How to iterate over stdClass?

As stated here:
http://us.php.net/manual/en/language.oop5.iterations.php

Normally, we iterate over an object by doing:

foreach($class as $key => $value)
{
print "$key => $value
";
}

But I’m not being able to do this with a stdClass object returned by fetch_all method using FETCH::OBJ option.

I get a:
Catchable fatal error: Object of class stdClass could not be converted to string

And I don’t understand what I’m doing wrong… :frowning:

What could it be?

Thanks in advance,
Márcio

Update:


$objRecord = $this->_daoh->listar();

The method that returns the object:

public function listar()
	
	{

		try
		
		{
			
			$query_str='SELECT * FROM table';
		
			$stmt = $this->_dbh->query($query_str);

			$records = $stmt->fetchAll(PDO::FETCH_OBJ);
		
			return $records;	
		}
		
		catch (PDOException $ex)
		
		{
			echo "Erro: " . $ex->getMessage();	
		}
			
	}

The try:

foreach ($objRecord as $property => $property_value)
{	
		
	print "$property => $property_value\
";
}

M. x_x

You are converting $property (an instance of stdClass), to a string;

    print "$property => $property_value\
";

Should just be;

    printf('$property => %s' . PHP_EOL, $property->property_value);

The method returns an array of objects not a single object.


foreach ($this->_daoh->listar() as $intIndex => $objRecord) {    
     print "$intIndex => {$objRecord->name}\
";
} 

Thanks you all. Well the main goal is to build a xls file from mysql data.
I’ve followed several examples, and I only see examples using mysql_num_rows, and mysql_num_fields, however, I’d like to do that using PDO, and if it makes more sense, to use the FETCH_OBJ for the effect.

Thanks. I’m not actually sure if I understand the concept of an array of objects. When I var_dump $objRecord it seems more that I’m inside an object, that object contains an array, and each key of that array that the object contains, corresponds to a column name that we have fetched.
Am I thinking wrong?

Since I want to grab the property names, to serve as columns on a xls file, maybe then, the foreach may be of no use in this case? :rolleyes:

So, if I’ve properly understood, that will output $property as a string, and then return his value as well… however, something like this:
inside the foreach,
foreach ($objRecord as $property => $property_value)
{
printf(‘$property => %s’ . PHP_EOL, $property->name);
}

Doesn’t seem to work: “Trying to get property of non-object” and it’s right, because, $property is no longer an object right? It was been converted into a string…?

Anyway, I’m getting away from the point.

The main point is, grab rows and columns form our database and put then on a xls, using PDO and fetch_obj for the effect. The question that rises is:
what ways do we have, to look into the object returned, and grab values and properties names and output that?

Regards,
Márcio

Ok… I was having only ONE record on my database, that’s why I wasn’t seeing any array before the stdClass when I var_dump.
Now that I have put two, I can now see that I’m over and array of lenght two, so, each record of my database is an object of stdClass, and inside of each one of those objects, the keys are corresponding to the table column names fetched.

I hope this is more precise…

So if we do:

foreach ( $objRecords as $record ) {
    foreach( $record as $column=>$value ) {
        echo "$column is $value\
";
    }
}

We are now grabbing the associate array key of each stdClass returned? :slight_smile:

Regards,
Márcio

Ok… :slight_smile: Almost…

I just need a way to grab the column names, anyone?
I mean, the Properties Names of ONE object. Since all the other objects will have the same Properties Names.

Could array_key play a rôle here? Or there is a better method for having the object property names print out?

public function xls ($file_name) 
{
    	
  $objRecord = $this->_daoh->listar();
		        
   //var_dump($objRecord);
        
   header('Content-type: application/x-msdownload; charset=UTF-8;');
   header('Content-Disposition: attachment; filename='.$nome_ficheiro.'.xls');
   header('Pragma: no-cache');
   header('Expires: 0');
        
    $xls_file ='';
		
     //$xls_file .= array_keys($objRecord);  
				
		
     foreach ($objRecord as $record)
     {	
        //for each objRecord we will have a new line.
        $xls_file .="\
";
			
			
        foreach ($record as $column=>$value) 
        {
           //for each record we will store each value on a new tab
           $xls_file .= $value."\	";
        }
			
      }
		
      print $xls_file;
					
}

Thanks,
M.

get_object_vars

Looking at the site, I see that that will give me also the values. Not only the properties names.
:frowning:

If I do this

$teste = get_object_vars($objRecord);
var_dump($teste);

I get false, I presume it is because objRecord is an array (of objects, as oddz stated, the the php manual as well…)

If I do this, inside the foreach, like so:

foreach ($objRecord as $record)
		{	
			$teste = get_object_vars($record);
			var_dump($teste);
			//for each objRecord we will have a new line.
			$xls_file .="\
";
(...)
			

Then I get properties AND also the values as well. :sick:

Use either;

array_keys(get_object_vars($objRecord[0]));

or

array_keys(get_object_vars($record));

Eehehe I was on my way…

the code I was trying:



foreach ($objRecord as $record)
		{	
			$teste = get_object_vars($record);
			
			$testea = array_keys($teste);
			
			var_dump($testea);

Anyway…

I don’t want to grab for each object on the array, the properties names, because, for all objects on this array of objects, the properties names will be the same. So, I just need them once. Hence, I should stay away of this foreach for that, yes? So maybe your first suggestion will work…

array_keys(get_object_vars($objRecord[0]));

I will give it a try…

Thanks,
M.

Nop. I’m getting (array) returned. :frowning:

$teste = array_keys(get_object_vars($objRecord[0]));

I’ve also tried with $objRecord[0][0] no success either…

Please think with me…
If we do foreach ($objRecord as $record)
$record will then be an $object.
And at that object we can apply:
$teste = array_keys(get_object_vars($record));
This will work.

However, it will NOT work if we use:
$objRecord[0]

But having this should work, I mean, if $objRecord is an array of objects, and it is, because var_dump as telling me that, if we then try to access the key [0] of that array, we should found, an object. :s

I will try to split this line:

array_keys(get_object_vars($objRecord[0]));

into to several steps… it’s stupid, but when I don’t know what to do anymore, I tend to be creative. :s

M.

Helllp!!! :S

Bah! Obvioulsy I do get a literal (array). In order to actually see his values, I need to grap the array values! :s

Bah! Sorry! It will work like a charm I hope.

:wink: Thanks a lot!
Márcio

oddz, fax, others…

For the records:

this seems quite nice:
http://pt.php.net/manual/en/reflectionproperty.getname.php

Regards,
Márcio