PHP生成具有多个数组的JSON

时间:2019-07-02 21:33:15

标签: php json

我想以这种格式生成json

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

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

}

到目前为止,我已经做到了

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


}
 echo (json_encode($ToSend_Json));

我为此得到的输出是在这种情况下的最后一个json

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

}

什么是正确的方法

1 个答案:

答案 0 :(得分:3)

您将在每次循环迭代时覆盖这些值。您应该为每次迭代使用一个数组。

$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);

或者,您可以使用foreach,这是迭代循环的更好方法:

$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);