TransWikia.com

PHP JsonEncode For MultiDimensional Array

Stack Overflow Asked by Kalui on December 31, 2020

Here’s the two arrays:

Array (
    [0] => https://google.com/
    [1] => https://bing.com/
)
    
Array (
    [0] => Google
    [1] => Bing
)

Here’s the output 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.

3 Answers

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 = [];

// 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"
//    }
//]

Correct answer by KodeFor.Me on December 31, 2020

$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.


Remark

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];
}

Answered by axiac on December 31, 2020

Your array should look like this:

$data = [
    ['url' => 'https://google.com/', 'name' => 'Google'],
    ['url' => 'https://bing.com/', 'name' => 'Bing'],
];

Answered by WoodyDRN on December 31, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP