phparraysjson

Warning: Attempt to read property "id" on array in C:\xampp\htdocs\admin\test.php on line


i want to echo massages id but i getting 'Warning: Attempt to read property' error

This is my code

<?php

$result ='{"num":1,"message":{"cont":"test"},"messages":[{"id":"123","rct":999}],"status":"success"}';



$obj = json_decode($result);

echo $obj->messages->id;

?>

Solution

  • You have to use like below because messages is also an array.

    $result ='{"num":1,"message":{"cont":"test"},"messages":[{"id":"123","rct":999}],"status":"success"}';
    
    $obj = json_decode($result,true);
    
    echo $obj['messages'][0]['id'];
    

    Or access it as an object, but messages is still an array

    $obj = json_decode($result);
    
    echo $obj->messages[0]->id;