php - 如何在 PHP 中从数组创建 JSON
问题描述
我想在 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}
}
解决方案
您$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);
推荐阅读
- reactjs - 无法访问函数外的数据
- shiny - 为什么条件面板在第一次尝试时不起作用?
- python - 实现自定义 max 函数的类
- c# - 通过点击编辑按钮 asp.net webforms 禁用 ModelPoPup 扩展器中的所有控件
- flutter - 制作全屏视频 Flutter
- python-3.x - 我需要从函数中导入一个变量。我该怎么做?
- windows - 缺少 UE4Game 二进制文件。您可能必须使用 IDE 构建 UE4 项目。或者,使用命令行
- django - 在 django 项目中集成 django-private-chat 时出错?
- c++ - 参数依赖查找和流运算符重载
- java - Thymeleaf + Spring boot 如何避免使用 GET 请求创建实例