Skip to content
Advertisement

How to convert Two dimentional array into Three dimentional in PHP?

I have below two dimentional array

$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]
];

And I want to convert this array into Three dimentional according to Parent-Child value like below array.

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

In this first iterator is value of ‘category’ key which iterate two times. second iteration is for ‘attribute’ and likewise third is for ‘option’, which iterate 8 times.

Addition: What if I want to do reverse. I have second array and want to convert in first one.

Thanks.

Advertisement

Answer

$arr = [
  ['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 = [];

foreach($arr as $arrRow) {
    $newArr[$arrRow['category']][$arrRow['attribute']][$arrRow['option']] = $arrRow['option'];
}

Strings with numbers for array keys will be converted to int in PHP.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement