如何从 PHP 中的数组创建 JSON

发布时间:2021-03-07 06:12

我想在 PHP 中使用数组和 foreach 循环创建一个 JSON 列表。 我正在尝试此代码:

    <?php
$test=array("Camera","Performance","Storage");
foreach ($test as $key=>$value){
$myArr = array($value=>array(
    "Rating" => "3",
    "Content" => "This is an Awesome content" ,
    "key" => $key
));
echo json_encode($myArr);
}

?>

我从这段代码得到这个输出:

 {"Camera":{"Rating":"3","Content":"This is an Awesome content","key":0}}

 {"Performance":{"Rating":"3","Content":"This is an Awesome content","key":1}}

 {"Storage":{"Rating":"3","Content":"This is an Awesome content","key":2}}

相反,我想要这样的输出:

 {
"Camera":{"Rating":"3","Content":"This is an Awesome content","key":0},

"Performance":{"Rating":"3","Content":"This is an Awesome content","key":1},

"Storage":{"Rating":"3","Content":"This is an Awesome content","key":2}
}
回答1

您每次都在循环中覆盖 $myArr。相反,每次都附加一个新的键/值对:

$test=array("Camera","Performance","Storage");
foreach ($test as $key => $value){
  $myArr[$value] = array(
      "Rating" => "3",
      "Content" => "This is an Awesome content",
      "key" => $key
  );
}

echo json_encode($myArr);