php - Parsing multi-dimensional array with json_decode

Solution:
You need to decode the data structure, then operate on it as you would any other PHP variables/objects/arrays.
<?php
// Raw JSON input
$input = '{
"name":"Server name",
"address":"***********",
"port":"****",
"month":"201601",
"voters":[
{
"nickname":"John",
"votes":"6"
},
{
"nickname":"Beth",
"votes":"4"
},
{
"nickname":"Jimmy",
"votes":"4"
}
]
}';
//Unserialize the JSON into PHP structures
$results = json_decode($input);
//$results is now an object with properties `name`, `address`, ..., `voters`, etc
// `$results->voters` is an indexed array of objects
// each of these objects have a `nickname` and `votes` property
// no need for a counter, use the index (gleaned from @trincot's answer)
foreach ($results->voters as $i => $voter) {
// I like `printf` here bcause it keeps my template cleaner to understand
printf(
'%s. %s (%s)<br />',
($i + 1),
$voter->nickname,
$voter->votes
);
}
Answer
Solution:
You could do it with this loop:
foreach ($results->voters as $i => $el) {
echo ($i+1) . ". {$el->nickname} ({$el->votes})<br/>";
}
Note that you need first to select the voters key, as you are not interested in the other keys at the top level.
Secondly, you're input has some objects (not arrays), so you need to use the->
operator to access the object properties.
Answer
Solution:
What you can do is:
$i=1;
foreach($result as $r)
{
echo $i . '. ' . $r['nickname'] . ' (' . $r['votes'] . ')<br \>';
$i++;
}
Answer
Solution:
You can use this code.
$string = '{"name":"Server name","address":"***********","port":"****","month":"201601","voters":[{"nickname":"John","votes":"6"},{"nickname":"Beth","votes":"4"},{"nickname":"Jimmy","votes":"4"}]}';
$result = json_decode($string);
// To print HTML using DOM
echo "<ol>";
foreach($result->voters as $voter){
echo "<li>$voter->nickname ($voter->votes)</li>";
}
echo "</ol>";
Working here -> https://eval.in/507711
This code print this HTML
<ol><li>John (6)</li><li>Beth (4)</li><li>Jimmy (4)</li></ol>
The result is here -> https://jsfiddle.net/h6q8zy86/
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: failed to create image decoder with message 'unimplemented'
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.