0

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

3
  • How does your while loop not infinite loop without an $i++? Commented Dec 2, 2013 at 2:45
  • The format your would like isn't a very good one. What if different objects have different statuses? Usually, having an object with just one property indicates bad design. Commented Dec 2, 2013 at 2:46
  • Im sorry, I forgot to paste that part in Commented Dec 2, 2013 at 2:47

1 Answer 1

2

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"
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

I think it'd be better to attach the status to each individual tagnumber group than to only have one for the entire user.
Well that's not what he/she requested.
@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.
@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
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.