php - Create a nested array -
i have table below
- id
- 1
- 2
- 4
- title
- home page
- about
- deneme
- slug
- home
- about
- deneme
- order
- 1
- 2
- 1
- body
- loremp ipsum
- dot sit
- color amet
- parent_id
- 2
- 0
- 0
now, want create nested array table. function below
public function get_nested () { $pages = $this->db->get('pages')->result_array(); $array = array(); foreach ($pages $page) { if (! $page['parent_id']) { $array[$page['id']] = $page; } else { $array[$page['parent_id']]['children'][] = $page; } } return $array; } dump($array);
when dump $array
dump => array(2) { [2] => array(6) { ["id"] => string(1) "2" ["title"] => string(5) "about" ["slug"] => string(5) "about" ["order"] => string(1) "2" ["body"] => string(241) "lorem ipsum dolor sit amet, consectetur adipisicing elit. ipsam itaque cumque ullam eum atque consectetur voluptates veritatis sapiente voluptatem voluptatibus neque, commodi reprehenderit odit dignissimos omnis, veniam et deserunt incidunt!" ["parent_id"] => string(1) "0" } [4] => array(6) { ["id"] => string(1) "4" ["title"] => string(6) "deneme" ["slug"] => string(6) "deneme" ["order"] => string(1) "1" ["body"] => string(13) "deneme" ["parent_id"] => string(1) "0" } }
there 2 page list in array there 3 page 1 has parent_id. page has parent_id not showing up. error in else block of get_nested function. error ?
thoroughly @ code , realize when first executes (for parent_id =2
),
$array[$page['parent_id']]['children'][] = $page;
it find $array[2] ($array [2] ['children'] [ ]
) doesn't exists. possible solution sort (orderby) query in ascending order of parent_id.
Comments
Post a Comment