php求助如何将二维数组变成一维数组?

现在有一个二维数组格式如下:

Array
(
    [0] => Array
        (
            [id] => 38
            [goods_id] => 77426
            [model_name] => 颜色
            [model_sub_name] => Array
                (
                    [0] => 黑色
                    [1] => 白色
                    [2] => 红色
                    [3] => 浅蓝色
                    [4] => 紫色
                )

            [goods_stock] => Array
                (
                    [0] => 321
                )

            [curr_price] => Array
                (
                    [0] => 99
                )

            [goods_weight] => Array
                (
                    [0] => 280
                )

        )

    [1] => Array
        (
            [id] => 39
            [goods_id] => 77426
            [model_name] => 尺码
            [model_sub_name] => Array
                (
                    [0] => 32A
                    [1] => 34A
                    [2] => 36A
                    [3] => 32B
                    [4] => 34B
                    [5] => 36B
                    [6] => 38B
                    [7] => 34C
                    [8] => 36C
                    [9] => 38C
                    [10] => 40C
                    [11] => 
                )

            [goods_stock] => Array
                (
                    [0] => 321
                )

            [curr_price] => Array
                (
                    [0] => 99
                )

            [goods_weight] => Array
                (
                    [0] => 280
                )

        )

)

现在需要将这个二维数组变成如下格式:

Array
(
    [0] => Array
        (
            [model_name] => 颜色
            [model_sub_name] => 黑色
            [goods_stock] => 321
            [curr_price] => 99
            [goods_weight] => 280

        )
    [1] => Array
        (
            [model_name] => 颜色
            [model_sub_name] => 白色
            [goods_stock] => 321
            [curr_price] => 99
            [goods_weight] => 280

        )
        ……这里省略N个数组

    [N+1] => Array
        (
            [model_name] => 尺码
            [model_sub_name] => 32A
            [goods_stock] => 321
            [curr_price] => 99
            [goods_weight] => 280
               
        )
    [N+2] => Array
        (
            [model_name] => 尺码
            [model_sub_name] => 34A
            [goods_stock] => 321
            [curr_price] => 99
            [goods_weight] => 280
               
        )
    这里也省略总数组第二个元素的几条记录
)

在上述数组中goods_stock、curr_price、goods_weight都是数组,如果这几个键中的数组只有一个元素,那么在model_name一样的前提下,goods_stock、curr_price、goods_weight都取这一个值,否则,就取model_sub_name中元素下标对应的goods_stock、curr_price、goods_weight中的值。比如model_sub_name为“白色”时对应的下标是1,上述数组中goods_stock、curr_price、goods_weight都只有一个元素,那么就取这一个元素的值,如果不是一个元素,则取goods_stock[1]、curr_price[1]、goods_weight[1]的值,不知道这样的描述是否理解。求助大神帮忙解决一下。

红颜莎娜
浏览 444回答 2
2回答

慕田峪9158850

需要先设置一个空数组,然后两层循环,第一层循环大数组,第二层循环里面的model_sub_name,然后给空数组赋值就行了
打开App,查看更多内容
随时随地看视频慕课网APP