开发者

PHP Arrays - Trying to get property of non-object

开发者 https://www.devze.com 2023-02-23 20:28 出处:网络
I am still new to PHP so please bear with me. So I am getting this error: Notice: Trying to get property of non-object on this line:

I am still new to PHP so please bear with me.

So I am getting this error: Notice: Trying to get property of non-object on this line:

echo (
            "<tr>".
            "<td>".$row->last_name.     "</td>".
            "<td>".$row->first_name.    "</td>".
            "<td>".$row->phone_no.      "</td>".
            "<td>".$row->date_of_birth. "</td>".
            "<td>".$row->membership.    "</td>".
            "</tr></table>");

I've used print_r on my function and I get:

Array
(
    [0] => Array
开发者_JS百科    (
        [0] => Lee
        [last_name] => Lee
        [1] => Lian
        [first_name] => Lian
        [2] => 39025823
        [phone_no] => 39025823
        [3] => 1967-09-19
        [date_of_birth] => 1967-09-19
        [4] => T
        [membership] => T
        [5] =>
        [status] =>
        [6] => 0
        [room_no] => 0
    )
)

So there are elements within the array.

The actual code falls under:

foreach($array as $row)
    {
            echo (
            "<tr>".
            "<td>".$row->last_name.     "</td>".
            "<td>".$row->first_name.    "</td>".
            "<td>".$row->phone_no.      "</td>".
            "<td>".$row->date_of_birth. "</td>".
            "<td>".$row->membership.    "</td>".
            "</tr></table>");
    }

I was thinking - how would I convert an array into an object? Maybe that would be my solution.


I was thinking - how would I convert an array into an object? Maybe that would be my solution.

That indeed would be one solution.

$row = (object) $row;

Another would be to use the right syntax for the data-type in question, in this case an array.

Instead of

$row->last_name

You should use

$row['last_name']


As you are working with an array, you should use [] to access the array's items :

echo $row['last_name'];

Use the right syntax, and the error will go away ;-)


Still, if you really want to convert an array to an object (not really sure why you'd do that, though, in this specific case), you can use this :

$row = (object)$row;
echo $row->last_name;

Here's the relevant section of the manual : Type Casting


Try this...

foreach($array as $row)
{
    echo (
        "<tr>".
        "<td>".$row['last_name'].     "</td>".
        "<td>".$row['first_name'].    "</td>".
        "<td>".$row['phone_no'].      "</td>".
        "<td>".$row['date_of_birth']. "</td>".
        "<td>".$row['membership'].    "</td>".
        "</tr></table>");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消