这是我的两个数组:
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 = [];
// Iterate 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"
// }
//]
$urls = [
'https://google.com/',
'https://bing.com/'
];
$names = [
'Google',
'Bing'
];
$combined = array_map(
fn($url, $name) => ['url' => $url, 'name' => $name],
$urls,
$names
);
echo(json_encode($combined));
当然,数组需要具有相同数量、相同顺序的元素。
查看它实际操作。
箭头函数 (
fn($url, $name) => ['url' => $url 'name' => $name]
) 仅适用于 PHP 7.4 及更高版本。function($url $name) {
return ['url' => $url, 'name' => $name];
}
甚至比 axiac 的代码片段更优雅,您可以对
get_defined_vars()
进行映射调用,这意味着您只需要在匿名函数的签名中按名称提及新密钥。
代码:(演示)
$urls = [
'https://google.com/',
'https://bing.com/'
];
$names = [
'Google',
'Bing'
];
echo json_encode(
array_map(
fn($url, $name) => get_defined_vars(),
$urls,
$names
),
JSON_PRETTY_PRINT
);
你的数组应该是这样的:
$data = [
['url' => 'https://google.com/', 'name' => 'Google'],
['url' => 'https://bing.com/', 'name' => 'Bing'],
];