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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top