Ok so I am trying to make a loop in php for json but I dont know what or how to loop it where I can keep the format I want for the JSON output. This is what i have:
$number = array(31,25,160);
$json_holder = array();
$counter = count($names);
$i = 0;
while($i < $counter){
$json_holder = array('user'=> array('results'=> array('tagnumber' => $number[$i],'status'=>'good'),);
echo json_encode($json_holder);
$i++;
}
And my output:
{"user":{"results":{"tagnumber":31,"status":"good"}}}
{"user":{"results":{"tagnumber":25,"status":"good"}}}
{"user":{"results":{"tagnumber":160,"status":"good"}}}
So instead of making new JSON root elements everytime I want to just make a new array in results so it would output like:
{
"user": {
"results": [{
"tagnumber": 31,
} {
"tagnumber": 25,
} {
"tagnumber": 160,
}],
"status": "okay"
}
}
I hope I am making sense
Navnath Godse
2,2252 gold badges25 silver badges33 bronze badges
1 Answer 1
Code
$number = array(31,25,160);
$payload = array('user' => array('results' => array(), 'status' => 'okay'));
foreach ($number as $num) {
$payload['user']['results'][]['tagnumber'] = $num;
}
echo json_encode($payload);
No need for a for() loop here.
Output
{
"user": {
"results": [
{
"tagnumber": 31
},
{
"tagnumber": 25
},
{
"tagnumber": 160
}
],
"status": "okay"
}
}
answered Dec 2, 2013 at 2:46
David
3,8112 gold badges31 silver badges38 bronze badges
Sign up to request clarification or add additional context in comments.
5 Comments
Kevin Ji
I think it'd be better to attach the
status to each individual tagnumber group than to only have one for the entire user.David
Well that's not what he/she requested.
Dave
@mc10: You are completely right but I am just starting to learn JSON and its concepts as this was something I needed to help put the piece to a puzzle together.
Dave
@David Great. A lot of clarity was provided with that answer. I dont know why I was so bent on using a for loop instead of a foreach. I can see how to structure this better now
David
It just makes it easier. Learning how to manipulate
array()s comes with time, and once you master them, it makes things like this a lot easier to work on.lang-php
whileloop not infinite loop without an$i++?