1

i want to generate json in this format

{
    "name": "item1",
    "description": "mydescript1"

}, 
{
    "name": "item2",
    "description": "mydescript2"

}

i have done this so far

for ($i = 0; $i<sizeof($name_); $i++){
    $ToSend_Json["name"]  = $name_[$i];
    $ToSend_Json["description"]  = $description_[$i];


}
 echo (json_encode($ToSend_Json));

the output i get for this is the last json which in this case is

 {
    "name": "item2",
    "description": "mydescript2"

}

what will be the correct way to do this

2
  • $ToSend_Json[$i]["name"] = $name_[$i]; $ToSend_Json[$i]["description"] = $description_[$i]; Commented Jul 2, 2019 at 21:37
  • That json is invalid as it has more then one top level node and no array around them [{...},{...}] Commented Jul 2, 2019 at 21:40

1 Answer 1

3

You're overwriting the values at each iteration of the loop. You should use an array for each iteration.

$json_array = [];

for ($i = 0; $i < count($name_); $i++){
    $ToSend_Json["name"] = $name_[$i];
    $ToSend_Json["description"] = $description_[$i];
    $json_array[] = $ToSend_Json;
}

echo json_encode($json_array);

Alternatively, you could use a foreach which is a better method for iterating a loop:

$json_array = [];

foreach ($name_ as $i => $name) {
    $ToSend_Json["name"] = $name;
    $ToSend_Json["description"] = $description_[$i];
    $json_array[] = $ToSend_Json;
}

echo json_encode($json_array);
Sign up to request clarification or add additional context in comments.

6 Comments

Array Push is a pointless, useless legacy function. All you need is $json_array[] = $ToSend_Json; - ie. no function calls.
There are also little point in the (json_encode($json_array)) extra (....) too. lol... sorry. It's ok, just ugly to me... haha
id suggest a foreach too;p
Or at least count instead of sizeof ... another function that needs to be removed. But foreach($name_ as $i => $value) then remove $ToSend_Json["name"] = $value; is much cleaner. In fact I wouldn't mind seeing how $name_ and $description_ are built there is likely some things there that could be better.
Okay, thanks for your suggestion @LawrenceCherone I've added it.
|

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.