Reputation: 1
Here are my two arrays:
Array (
[0] => https://google.com/
[1] => https://bing.com/
)
Array (
[0] => Google
[1] => Bing
)
Here's the output that I want in JSON:
[
{
"url": "https://google.com/",
"name": "Google"
},
{
"url": "https://bing.com/",
"name": "Bing"
}
]
I'm not able to get both the array in foreach loop and using json_encode to print them in JSON format.
Upvotes: -1
Views: 73
Reputation: 47894
Even more elegant than axiac's snippet, you can make mapped calls of get_defined_vars()
which means that you'll only need to mention the new keys by name in the anonymous function's signature.
Code: (Demo)
$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
);
See an earlier page on the topic of converting parameters and their values to an associative array: How can I convert a PHP function's parameter list to an associative array?
Upvotes: 0
Reputation: 13511
Note that this solution requires both arrays (in my case $domains and $names) have the entries in the same order.
$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"
// }
//]
Upvotes: 1
Reputation: 72226
$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));
Of course, the arrays need to have the same number of elements, in the same order.
See it in action.
The arrow function (fn($url, $name) => ['url' => $url 'name' => $name]
) works only on PHP 7.4 and newer versions.
For older versions use the full syntax for anonymous functions:
function($url $name) {
return ['url' => $url, 'name' => $name];
}
Upvotes: 1