You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

stdClass对象当作数组使用报错:分页实现关联标题表格时遇问题

Fixing "Cannot use object of type stdClass as array" Error After Adding Pagination

Hey there! Let's break down why you're hitting this error and how to fix it quickly.

The root issue here is that after adding pagination, your database query is returning stdClass objects instead of the associative arrays you were probably using before. When you try to access properties with array syntax like $item['column_name'], PHP throws an error because it can't treat an object like an array.

Here are 3 straightforward solutions:

1. Access the object directly with arrow syntax (->)

This is the simplest fix if you don't need an array. Since each item in your pagination result is a stdClass object, you can access its properties directly using the arrow operator:

// Example: Loop through your paginated results
foreach($paginatedResults as $item) {
    // Instead of $item['title'], use this:
    echo $item->title;
    echo $item->description;
}

2. Convert the object to an associative array

If you prefer to keep using array syntax (maybe you have existing code that relies on it), you can convert each stdClass object to an array. There are a couple ways to do this:

  • Casting: Quick and simple for basic objects
    foreach($paginatedResults as $item) {
        $itemArray = (array)$item;
        echo $itemArray['title'];
    }
    
  • JSON decode/encode: Better for nested objects (if your data has nested structures)
    foreach($paginatedResults as $item) {
        $itemArray = json_decode(json_encode($item), true);
        echo $itemArray['title'];
    }
    

3. Make your query return arrays from the start

If you're using an ORM or database library that supports it, you can configure the query to return associative arrays instead of objects. For example, in Laravel:

// Adjust pagination to return array items
$paginatedResults = DB::table('your_table')->paginate(10)->through(function($item) {
    return (array)$item;
});
// Now you can use array syntax in your loop
foreach($paginatedResults as $item) {
    echo $item['title'];
}

Quick Debug Tip

If you're not sure what type you're dealing with, add a var_dump($item); inside your loop. This will show you if it's a stdClass object or an array, so you know exactly which approach to take.


内容的提问来源于stack exchange,提问作者Alberto Delrio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:57:28