首页 > 解决方案 > 多维数组的PHP JsonEncode

问题描述

这是两个数组:

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 格式打印它们。

标签: php

解决方案


请注意,此解决方案要求两个数组(在我的情况下为 $domains 和 $names)具有相同顺序的条目。

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

推荐阅读