Asked  7 Months ago    Answers:  5   Viewed   35 times

I was trying to copy this code:

<?php
foreach ($products as $product) {
    $id          = $product['id'];
    $name        = $product['name'];
    $description = $product['description'];
    $price       = $product['price'];
?>
    <tr>
    <td><img src="<?php echo $product['picture']; ?>" /></td>
        <td><b><?php echo $name; ?></b><br />
        <?php echo $description; ?><br />
          Price:<big style="color:green">
          $<?php echo $price; ?></big><br /><br />
<?php
    echo form_open('cart/add');
    echo form_hidden('id', $id);
    echo form_hidden('name', $name);
    echo form_hidden('price', $price);
    echo form_submit('action', 'Add to Cart');
    echo form_close();
?>
    </td>
    </tr>
    <tr><td colspan="2"><hr size="1" /></td>
<?php
}
?>

and here is my code:

<?php
   foreach ($blogs as $blog) {
      $id      = $blog['id'];
      $title   = $blog['title'];
      $content = $blog['content'];
?>
      <h1><?php echo $title; ?></h1>
      <h1> <?php echo $content; ?> </h1>

<?php
}
?>

I get this error every time I run my code: "Cannot use object of type stdClass as array"

 Answers

57

The example you copied from is using data in the form of an array holding arrays, you are using data in the form of an array holding objects. Objects and arrays are not the same, and because of this they use different syntaxes for accessing data.

If you don't know the variable names, just do a var_dump($blog); within the loop to see them.

The simplest method - access $blog as an object directly:

Try (assuming those variables are correct):

<?php 
    foreach ($blogs as $blog) {
        $id         = $blog->id;
        $title      = $blog->title;
        $content    = $blog->content;
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?>

The alternative method - access $blog as an array:

Alternatively, you may be able to turn $blog into an array with get_object_vars (documentation):

<?php
    foreach($blogs as &$blog) {
        $blog     = get_object_vars($blog);
        $id       = $blog['id'];
        $title    = $blog['title'];
        $content  = $blog['content'];
?>

<h1> <?php echo $title; ?></h1>
<h1> <?php echo $content; ?> </h1>

<?php } ?> 

It's worth mentioning that this isn't necessarily going to work with nested objects so its viability entirely depends on the structure of your $blog object.

Better than either of the above - Inline PHP Syntax

Having said all that, if you want to use PHP in the most readable way, neither of the above are right. When using PHP intermixed with HTML, it's considered best practice by many to use PHP's alternative syntax, this would reduce your whole code from nine to four lines:

<?php foreach($blogs as $blog): ?>
    <h1><?php echo $blog->title; ?></h1>
    <p><?php echo $blog->content; ?></p>
<?php endforeach; ?>

Hope this helped.

Wednesday, March 31, 2021
 
Null
answered 7 Months ago
39

You are actually trying to access the object as array.

I can guess you are having problem when you are using json_decode which is returning an object and inside the foreach loop you are trying to access it like an associative array.

Passing the second argument as true to json_decode force it to return associative array.

Make the below change.

Change your this code line

$items = json_decode($contents);

To

$items = json_decode($contents, true);
Wednesday, March 31, 2021
 
ALH
answered 7 Months ago
ALH
92

If you could index the array by gear or some unique value, it would be a lot easier.

$indexed = array();

// create an array using 'gear' as the index
foreach($arrayValue as $value) {
    $indexed[$value['gear']] = $value;
}

// loop over each object
foreach($objectArray as $obj) {
    $value = $indexed[$obj->gear]; // find the corresponding array
    foreach($value as $name => $val) {
        $obj->$name = $val; // assign each array index/value pair to the object
    }
}

If possible to get your code to return the array with the index by default, you can remove the first foreach loop.

Hope that helps.

Wednesday, March 31, 2021
 
wavyGravy
answered 7 Months ago
33

I think the issue with your code is that when fetching the records from the database they are being returned as object and you are trying to use that object as if it was an array.

You have 2 solutions, solution 1 is the most efficient:

Solution 1: Use the variable $row as an object instead of an array

foreach($table as $row) {
    fputcsv($handle, array( $row->id, $row->name, $row->phonenumber, $row->email,$row->umur, $row->tempattinggal,$row->bank, $row->kartukredit, $row->rumah,$row->keluarnegeri, $row->penghasilan ));
}

Solution 2: Convert the $row to an array for every loop

foreach($table as $row) {
    $row = json_decode(json_encode($row), True);
    //Or $row = (array)$row;
    fputcsv($handle, array( $row['id'], $row['name'], $row['phonenumber'], $row['email'],$row['umur'], $row['tempattinggal'],$row['bank'], $row['kartukredit'], $row['rumah'],$row['keluarnegeri'], $row['penghasilan'] ));
}
Saturday, May 29, 2021
 
conmen
answered 5 Months ago
10

You either iterate the array, searching for the particular record (ok in a one time only search) or build a hashmap using another associative array.

For the former, something like this

$item = null;
foreach($array as $struct) {
    if ($v == $struct->ID) {
        $item = $struct;
        break;
    }
}

See this question and subsequent answers for more information on the latter - Reference PHP array by multiple indexes

Saturday, June 5, 2021
 
TMichel
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :