php - 多维数组的PHP JsonEncode
问题描述
这是两个数组:
Array (
[0] => https://google.com/
[1] => https://bing.com/
)
Array (
[0] => Google
[1] => Bing
)
这是我想要的 JSON 输出:
[
{
"url": "https://google.com/",
"name": "Google"
},
{
"url": "https://bing.com/",
"name": "Bing"
}
]
我无法在 foreach 循环中获取数组并使用 json_encode 以 JSON 格式打印它们。
解决方案
请注意,此解决方案要求两个数组(在我的情况下为 $domains 和 $names)具有相同顺序的条目。
$domains = [
'https://google.com/',
'https://bing.com/'
];
$names = [
'Google',
'Bing'
];
$output = [];
// Itterate over the domains
foreach($domains as $key => $value){
// And push into the $output array
array_push(
$output,
// A new array that contains
[
// the current domain in the loop
"url" => $value,
// and the name, in the same index as the domain.
"name" => $names[$key]
]
);
}
// Finally echo the JSON output.
echo json_encode($output);
// The above line will output the following:
//[
// {
// "url": "https://google.com/",
// "name": "Google"
// },
// {
// "url": "https://bing.com/",
// "name": "Bing"
// }
//]
推荐阅读
- python - 将 PPTx 导出为 PDF(使用 win32com 或 comtypes 发出问题)
- java - Maven 依赖 - 从版本管理?
- python - 在 tkinter 中使用带有图像的按钮的下拉菜单
- laravel - Laravel 8:Session::forget() 在刀片文件中不起作用
- error-handling - 为什么编译后出现这些错误
- c - 是否可以通过 C 中的预处理器指令计算斐波那契数列?
- mysql - MySQL SELECT 查询仅对 300k 行运行非常慢
- pyaudio - 无法使用 pyaudio 录制音频
- firebase - Dart-Flutter 中的异步函数错误
- vue.js - Vue:无效的道具:道具的类型检查失败。预期的数组,得到带有值的字符串