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
joeybab3
3172 gold badges9 silver badges26 bronze badges
asked Jul 2, 2019 at 21:33
6563cc10d2
1931 gold badge2 silver badges9 bronze badges
1 Answer 1
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);
answered Jul 2, 2019 at 21:36
Jerome
9041 gold badge12 silver badges40 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
ArtisticPhoenix
Array Push is a pointless, useless legacy function. All you need is
$json_array[] = $ToSend_Json; - ie. no function calls.ArtisticPhoenix
There are also little point in the
(json_encode($json_array)) extra (....) too. lol... sorry. It's ok, just ugly to me... hahaLawrence Cherone
id suggest a foreach too;p
ArtisticPhoenix
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.Jerome
Okay, thanks for your suggestion @LawrenceCherone I've added it.
|
lang-php
$ToSend_Json[$i]["name"] = $name_[$i]; $ToSend_Json[$i]["description"] = $description_[$i];[{...},{...}]