views:

63

answers:

2

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 ;)

A: 

It looks like you want to take an Array of pages and turn it into an array of categories with each containing an array of pages.

$inputArray = array(...); // whatever you have originally
$catArray = array();
foreach($inputArray as $page) {
  addToCatArray($page);
}

function addToCatArray($page) {
  $found = false;
  foreach($catArray as $cat) {
    if ($cat['c_cat_id'] == $page['c_cat_id'] {
      $newPage = array('p_page_id' => $page['p_page_id'], 'p_menu' => $page['p_menu']);
      $cat['pages'][] = $newPage;
      $found = true;
      break;
    }
  }
  if (!$found) { // create a new category
    $newCat = array('c_cat_id' => $page['c_cat_id'], 'c_title' => $page['c_title']);
    $newPage = array('p_page_id' => $page['p_page_id'], 'p_menu' => $page['p_menu']);
    $newCat['pages'] = array($newPage);
    $catArray[] = $newCat;
  }
}
Fletcher Moore
Yeah sorry if I wasn't that clear but this is exactly what I want.
Fverswijver
+1  A: 
gnarf
Works like a charm, thank's a lot ;)
Fverswijver
Way cooler than mine :-/
Fletcher Moore