-2

I wanted to output a 3 dimensional array that will come from the Database. This is my database looks like:

enter image description here

Basically, I wanted my first array will be the header_name and under the header_name the sub_header_name will come then underneath is the name

eg:

    User Role Management => array(
                          '' => array (
                                   'Create User Role'
                               ) 
                            ),
   Config Management => array(
                         'Organisation' => array('Create Country','Create 
                                           Organisation'),
                          'Site' => array('Create Site','Edit Site') 
                        )

and here are my codes:

$getAllPermission = Permission::get();
$arrHeader = array();
$arrSubHeader = array();
$arrPermissions = array();
// $x = 0;
foreach($getAllPermission as $value){
    $title = $value->header_name;
    $sub_header_name = $value->sub_header_name;
    $permission_name = $value->name;
    if ($sub_header_name == ""){
        $sub_header_name = 0;
    }
    array_push($arrPermissions,$permission_name);
    $arrHeader[$title] = array($sub_header_name => array($arrPermissions));
    //$x++;

}

and my output was like this:

enter image description here

Barmar
  • 741,623
  • 53
  • 500
  • 612
kevin_marcus
  • 277
  • 1
  • 5
  • 19

1 Answers1

1

You're pushing onto the same $arrPermissions array every time through the loop, that's why each of the roles gets a longer and longer copy of the permissions array.

You're overwriting $arrHeader[$title] each time through the loop instead of adding a new key to it.

Your desired output has a key of '' for the empty sub_header_name, so I don't see why you have the if that sets $sub_header_name = 0;.

It should simply be:

foreach ($getAllPermissions as $value) {
    $arrHeader[$value->header_name][$value->sub_header_name][] = $value->name;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612