phparraysmultidimensional-array

php transform array into multidim array


So I'm working on a website with Doctrine as ORM and I get the following array back as a result:

Array (
    [0] => Array (
        [c_cat_id] => 1
        [c_title] => Programas e projetos
        [p_menu] => PBA BR 163
        [p_page_id] => 1
    )
    [1] => Array (
        [c_cat_id] => 1
        [c_title] => Programas e projetos
        [p_menu] => Outros projetos
        [p_page_id] => 3
    )
) 

Is it possible to transform this array (in PHP) to something like this:

Array (
    [0] => Array (
        [c_cat_id] => 1
        [c_title] => Programas e projetos
        [pages] => Array (
            [0] => Array (
                [p_page_id] => 1
                [p_menu] => PBA BR 163
            )
            [1] => Array (
                [p_page_id] => 3
                [p_menu] => Outros projetos
            )
        )
    )
)

Thanks for your help, always eager to learn new ways of doing things and that's why I love StackOverflow ;)


Solution

  • Tested and working:

    Code:

    $original = array(
      array(
        "c_cat_id" => "1",
        "c_title" => "Programas e projetos",
        "p_menu" => "PBA BR 163",
        "p_page_id" => "1"),
      array(
        "c_cat_id" => "1",
        "c_title" => "Programas e projetos",
        "p_menu" => "Outros projetos",
        "p_page_id" => "3"),
      array(
        "c_cat_id" => "2",
        "c_title" => "Another Cat",
        "p_menu" => "Outros projetos",
        "p_page_id" => "4"),
    );
    $result = array();
    
    foreach ($original as $row) {
      $cat = $row['c_cat_id'];
      if (!isset($result[$cat])) {
        $result[$row['c_cat_id']] = array(
          'c_cat_id'=>$row['c_cat_id'],
          'c_title'=>$row['c_title'],
          'pages'=>array(),
        );
      }
      unset($row['c_cat_id'],$row['c_title']);
      $result[$cat]['pages'][] = $row;
    }
    
    var_dump($result);
    

    Result:

    array(2) {
      [1]=>
      array(3) {
        ["c_cat_id"]=>
        string(1) "1"
        ["c_title"]=>
        string(20) "Programas e projetos"
        ["pages"]=>
        array(2) {
          [0]=>
          array(2) {
            ["p_menu"]=>
            string(10) "PBA BR 163"
            ["p_page_id"]=>
            string(1) "1"
          }
          [1]=>
          array(2) {
            ["p_menu"]=>
            string(15) "Outros projetos"
            ["p_page_id"]=>
            string(1) "3"
          }
        }
      }
      [2]=>
      array(3) {
        ["c_cat_id"]=>
        string(1) "2"
        ["c_title"]=>
        string(11) "Another Cat"
        ["pages"]=>
        array(1) {
          [0]=>
          array(2) {
            ["p_menu"]=>
            string(15) "Outros projetos"
            ["p_page_id"]=>
            string(1) "4"
          }
        }
      }
    }