如何在PHP中将3维数组转换为2维数组?

问题描述 投票:0回答:2

我有以下 3D 数组:

$data = [

    '1'=>[
        '1' => [
            '1' => 1,
            '2' => 2        
        ],
        '2' => [
            '3' => 3,
            '4' => 4        
        ]
    ],
    '2'=>[
        '3' => [
            '5' => 5,
            '6' => 6        
        ],
        '4' => [
            '7' => 7,
            '8' => 8        
        ]
    ],
];

在此数组中,第一个迭代器用于“类别”,它应该只迭代两次。第二个迭代器用于“属性”,应迭代四次,第三个迭代器有 8 个值,用于“选项”。

输出应类似于下面的二维数组。

$data = [

    ['category'=>1,'attribute'=>1,'option'=>1],
    ['category'=>1,'attribute'=>1,'option'=>2],
    ['category'=>1,'attribute'=>2,'option'=>3],
    ['category'=>1,'attribute'=>2,'option'=>4],
    ['category'=>2,'attribute'=>3,'option'=>5],
    ['category'=>2,'attribute'=>3,'option'=>6],
    ['category'=>2,'attribute'=>4,'option'=>7],
    ['category'=>2,'attribute'=>4,'option'=>8]
];

我已经这样做了:

$newarr = array();

foreach ($data as $subarray){

    foreach ($subarray as $key => $value) {

        foreach ($value as $k => $v) {

        $newarr[$v] = array('category' => $subarray,'attribute'=>$value,'option'=>$v);
        }
    }
}


print_r($newarr);

但是我只能获取选项的值,而不是类别和属性值。

谢谢。

php arrays multidimensional-array
2个回答
1
投票

您的代码已接近;你可以使用嵌套的 foreach 循环生成你想要的输出,但是你必须将每个级别的 keys 保存到类别和属性值中,然后将一个值推入最内层循环的结果数组中:

$result = [];
foreach ($data as $category => $attributes) {
    foreach ($attributes as $attribute => $options) {
        foreach ($options as $option) {
            $result[] = array('category' => $category, 'attribute' => $attribute, 'option' => $option);
        }
    }
}

输出:

Array
(
    [0] => Array
        (
            [category] => 1
            [attribute] => 1
            [option] => 1
        )
    [1] => Array
        (
            [category] => 1
            [attribute] => 1
            [option] => 2
        )
    [2] => Array
        (
            [category] => 1
            [attribute] => 2
            [option] => 3
        )
    [3] => Array
        (
            [category] => 1
            [attribute] => 2
            [option] => 4
        )
    [4] => Array
        (
            [category] => 2
            [attribute] => 3
            [option] => 5
        )
    [5] => Array
        (
            [category] => 2
            [attribute] => 3
            [option] => 6
        )
    [6] => Array
        (
            [category] => 2
            [attribute] => 4
            [option] => 7
        )
    [7] => Array
        (
            [category] => 2
            [attribute] => 4
            [option] => 8
        )
)

3v4l.org 上的演示


0
投票

迭代三个级别的数据,并使用

compact()
根据每个所需行的变量名称简洁地生成关联元素。 演示

$result = [];
foreach ($data as $category => $attributes) {
    foreach ($attributes as $attribute => $options) {
        foreach ($options as $option) {
            $result[] = compact('category', 'attribute', 'option');
        }
    }
}
var_export($result);
© www.soinside.com 2019 - 2024. All rights reserved.