PHP Arrays - Attempting to get a non-object property

I'm still new to PHP, so please bear with me.

So, I get this error: Note. Trying to get a non-object property 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 used print_r for my function and I get:

 Array ( [0] => Array ( [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 in the array.

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 thought: how do I convert an array to an object? Perhaps that would be my decision.

+4
source share
3 answers

I thought: how do I convert an array to an object? Perhaps that would be my decision.

That would really be one solution.

 $row = (object) $row; 

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

Instead

 $row->last_name 

You have to use

 $row['last_name'] 
+10
source

When you work with an array, you must use [] to access the elements of the array:

 echo $row['last_name']; 

Use the correct syntax and the error will disappear; -)


However, if you really want to convert the array to an object (not quite sure why you will, in this particular case), you can use this:

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

Here is the relevant section of the manual: Type Casting

+5
source

Try it...

 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>"); } 
+4
source

Source: https://habr.com/ru/post/1347486/


All Articles