Iterating Through a Stdclass Object in PHP

How to iterate through a nested stdClass?

echo "<table>"

foreach ($object->values as $arr) {
foreach ($arr as $obj) {
$id = $obj->group->id;
$name = $obj->group->name;

$html = "<tr>";
$html .= "<td>Name : $name</td>";
$html .= "<td>Id : $id</td>";
$html .= "</tr>";
}
}

echo "</table>";

PHP Loop stdClass Object

You can json_decode as associative array.

$response = json_decode ($response, true);

foreach($response as $orders) {
echo $orders[0]['orderid'];
}

PHP loop through array of stdClass object

Easy enough. Loop through the array and access the object and the color property and assign it to a new array element:

foreach($array as $object) {
$colors[] = $object->color;
}

Looping Through a stdClass Object in PHP

You have an array of objects. Each object has properties that can be referenced.

So, for the array $result, you can iterate through the array.

foreach($result as $row) {}

Each row, however, is an object; properties of an object are referenced like so: $row->Document_No

So if you were wanting to print out a table using fields [Document_No] [Line_No][Description] [Type] [Quantity], you could do this:

<?php
// do whatever to get $result

// php logic finished...
?>
<table>
<tr>
<th>Document_No</th>
<th>Line_No</th>
<th>Description</th>
<th>Type</th>
<th>Quantity</th>
</tr>
<?php foreach($result as $row): ?>
<tr>
<td><?= $row->Document_No ?></td>
<td><?= $row->Line_No ?></td>
<td><?= $row->Description?></td>
<td><?= $row->Type ?></td>
<td><?= $row->Quantity ?></td>
</tr>
<?php endforeach; ?>
</table>

For a form, the same idea applies:

<?php foreach($result as $index => $row): ?>
<input disabled id="description" class="form-control input-group-lg reg_name" name=“description[<?= $index ?>]” value=“<?= $row->Description?>” >

...
<?php endforeach; ?>

stdClass Object In Array Iteration

This is easily enough done with array_column() to get the ID values; it works just as well with objects as it does with arrays.

<?php
// some sample data
$results = json_decode('[{"ID": 1}, {"ID": 2}, {"ID": 3}]');

$return = implode(",", array_column($results, "ID"));
echo $return;

Output:

1,2,3

How can I loop stdClass in PHP?

You will have to iterate through _results (or maybe even try results (I do not know which framework or library you use for database communication)):

foreach($data->_results as $item) {
echo $item->username; // first result should be: jonathan@gmail.com
}

EDIT: As you have defined a public getter method results() which safely returns your private $_results variable, you can do the following:

foreach($data->results() as $item) {
echo $item->username; // first result should be: jonathan@gmail.com
}

It will work now.



Related Topics



Leave a reply



Submit