Search code examples
phparraysmultidimensional-arraymappingassociative-array

Join two flat, indexed arrays (by index) to form an indexed array of associative rows with hardcoded keys


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.


Solution

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