Reputation: 793
I made this question 3 days ago, but unfurtunaly I couldn't solve my problem till now. I will formulate the question again with the hope that somebody help me.
I have the following JSON structure
{"Id":"1","Persons":[{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},{"Name":"Ben","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
To the element Id
is not a problem to access. I can get this value like this:
$arr['Id'] = $_POST['Id'];
echo $arr['Id'];
But if want to access to the structure Persons
inside of the JSON, specifically to the Time value of each Person, I do like this:
$arr['Persons'] = $_POST['Persons'];
$jsdecode = json_decode($arr['Persons']);
foreach ($arr['Persons'] as $p){
echo "$p->Time <br/>";
}
And this is the result that get:
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>38</b><br />
<br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/><br />
<b>Notice</b>: Trying to get property of non-object in <b>C:\xampp\htdocs\Stopuhr\controller\prozess.controller.php</b> on line <b>41</b><br />
<br/>
Can PLEASE somebody help me?
Upvotes: 3
Views: 58
Reputation: 19
You have a syntax error:
{"Id":"1","Persons":[
{"Name":"Luis","Time":"00:00:09","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""},
{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}
]}
no comma before Name Louis.
You should always validate your encoded json on http://jsonlint.com/
Upvotes: 1
Reputation: 2697
json_encode() - PHP Array to JSON
The json_encode()
method will take a PHP array and encode it as JSON ready to be consumed by an AJAX call.
$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');
$myJson = json_encode($myarray);
echo $myJson;
json_decode() - JSON to PHP Array
json_decode()
will take JSON and convert it into a PHP array.
$myJson = '{"Guitar" : "Johnny", "Vocals": "Stephen", "Bass" : "Andy", "Drums" : "Mike"}';
$myarray = json_decode($myJson, true);
print_r($myarray);
Upvotes: 2