在PHP中,如何首先在子数组上迭代输出JSON,然后在父数组上迭代


In PHP, how do you output JSON iterating first on a child array, then on parent?

我已经尝试了几个星期来实现这一点,但已经让步了。我需要用JSON显示以下数组。

正如您所看到的,[coloroptions]本身就是一个JSON数组,使其成为一个多维数组。诀窍是(我认为)在数组上迭代,首先在子对象[colorkoptions]上,然后在父对象上。不过,我可能离基地太远了。有人做过这样的事吗?

提前谢谢!

来自print_r()的样本数据

    Array
    (
        [0] => Array
            (
                [id] => 1
                [automobile] => 'Mustang'
                [coloroptions] => [{"color":"red"},{"color":"blue"},{"color":"green"}]
            )
        [1] => Array
            (
                [id] => 2
                [automobile] => 'Camero'
                [coloroptions] =>  [{"color":"red"},{"color":"orange"}]
            )
    )

JSON输出

    [
        {
            "id": 1,
            "automobile": "Mustang",
            "color": "red"
        },
        {
            "id": 1,
            "automobile": "Mustang",
            "color": "blue"
        },
        {
            "id": 1,
            "automobile": "Mustang",
            "color": "green"
        },
        {
            "id": 2,
            "automobile": "Camero",
            "color": "red"
        },
        {
            "id": 2,
            "automobile": "Camero",
            "color": "orange"
        },
    ]

我想你已经接近了!我的方法是对颜色使用json_decode,并像普通的PHP数组一样对它们进行迭代。

// First, start by looping through each 'parent':
foreach($array as $key => $value)
{
    // Decode the json color array into a normal php array
    $colorarray = json_decode($value['coloroptions'], true);
    /* Loop through each of the colours.
       (Note that they'll be a few layers deep. 
       Do a print_r($colorarray) to see it's structure)  */
    foreach($colorarray as $color)
    {
       // And build your output array:
        $output[] = array(
            "id" => $value['id'], 
            "automobile" => $value['automobile'],
            "color" => $color['color']
        );
    }
}

要检查最终的PHP数组,您可以print_r($output)。要将$output转换为json数组,请使用json_encode

json_encode($output);

好吧,您需要json_decode coloroptions,并将包含颜色的组合数组输出到结果数组。

$a = array(
    array(
        'id'           => 1,
        'automobile'   => 'Mustang',
        'coloroptions' => '[{"color":"red"},{"color":"blue"},{"color":"green"}]'
        ),
    array(
        'id'           => 2,
        'automobile'   => 'Camero',
        'coloroptions' => '[{"color":"red"},{"color":"orange"}]'
        ),
    );
$result = array();
foreach($a as $key => $value) {
    $coloroptions = json_decode($value['coloroptions']);
    foreach($coloroptions as $color){
        $result[] = array(
            'id'         => $value['id'],
            'automobile' => $value['automobile'],
            'color'      => $color->color,
            );
    }
}
print_r(json_encode($result));

请参阅此处的示例