phparraysmultidimensional-arraytranspose

Transpose and restructure data sets within a multidimensional array


I am working on a multi-dimensional array. This is my original array:

$oriArr = array(
   2 => array( 
      "A" => 'Mapping item1', 
      "B" => array(1 => 'product1', 2 => 'product2', 3 => 'product3'), 
      "C" => array(1 => 'item1', 2 => 'item2', 3 => 'item3') 
    ), 
   3 => array( 
      "A" => 'Mapping item2', 
      "B" => array(1 => 'product4', 2 => 'product5', 3 => 'product6') 
      "C" => array(1 => 'item4', 2 => 'item5', 3 => 'item6') 
    ) 
 );

What I am trying to do is to converting the original array into the array like this:

$resArr = array(
   "Mapping item1" => array(
      1 => array("product1", "item1"),
      2 => array("product2", "item2"),
      3 => array("product3", "item3"), 
   ),
   "Mapping item2" => array(
      1 => array("product4", "item4"),
      2 => array("product5", "item5"),
      3 => array("product6", "item6"), 
   ),
);

I tried to use array_column() but the function only allows array with 2 columns, my original array has 3 columns A,B,C. Any suggestions?


Solution

  • Try the following function.

    function my_merge_array( $arr = [] ){
        $result = [];
        foreach ( $arr as $_arr ) {
            $A = $_arr['A'];
            foreach ($_arr['B'] as $key => $value) {
                $result[$A][$key] = [ $value, $_arr['C'][$key] ];
            }
        }
        return $result;
    }
    
    print_r( my_merge_array( $oriArr ) );