PHP Transition Hierarchy

I want to create hierarchical Enumarations for my PHP applications and thought about things like

abstract class User_Roles extends Enum {

    const Administrator = "";
    const Account_Manager = "Administrator";
    const BlogAuthor = "Account_Manager";
    const CommentManager = "Account_Manager";

}

I am using this Enum-Class: stack overflow

So, every child has a parent Node as its value.

Here is how I did it:

    $constants = $reflector->getConstants();
    foreach ($constants as $key => $value) {
        if ($value == "") {
           $returnHierarchy[$key] = array();
           continue;
        }
        $returnHierarchy[][$value] = $key;
    }

But I have some problems with the multidimensional array that I want to create.

So it should look like this:

[Administrator]
{
    [Account_Manager]
    {
        [BlogAuthor]
        [CommentManager]
    }
}

But in the end I get things like this:

array(4) (
  [Administrator] => array(0)
  [0] => array(1) (
    [Administrator] => (string) Account_Manager
  )
  [1] => array(1) (
    [Account_Manager] => (string) BlogAuthor
  )
  [2] => array(1) (
    [Account_Manager] => (string) CommentManager
  )
)

Is there something that I misunderstand or don’t notice?

+4
source share
1 answer

You need to run a loop $contstantsand search inside yours $returnHierarchyif your role $valuehas already been added, if not create a new one

,

// IMPORTANT: it return reference function mae mast start with &
function &searchKeyInArray($key, &$array){

        $matchedArrayReffarance = null;

        if( !isset($array[$key]) ){

            foreach ($array as &$sub){

                if(is_array($sub)){
                    $matchedArrayReffarance = &searchKeyInArray($key, $sub);
                }
            }
        }else{
            $matchedArrayReffarance = &$array;
        }

        return $matchedArrayReffarance;
}

, searchKeyInArray, , .

$returnHierarchy = array();
// This is example, in your case it is: $constants = $reflector->getConstants();
$constants = array(
        'Administrator' => "",
        'Account_Manager' => "Administrator",
        'BlogAuthor' => "Account_Manager",
        'CommentManager' => "Account_Manager",
);

foreach ($constants as $key => $value) {

    $matchArray = &searchKeyInArray($value, $returnHierarchy);

    if( isset($matchArray) ){
        $matchArray[$value][$key] = array();
    }else{
        $returnHierarchy[$key] = array();
    }
}

var_dump($returnHierarchy);

var_dump $returnHierarchy

array(1) { 
    ["Administrator"]=> &array(1) { 
          ["Account_Manager"]=> array(2) { 
              ["BlogAuthor"]=> array(0) { } 
              ["CommentManager"]=> array(0) { } 
          } 
    } 
}
+1

Source: https://habr.com/ru/post/1628748/


All Articles