игорь88 игорь88 - 11 months ago 99
PHP Question

Convert array of strings into multi-dimensional array

How to convert array of strings:

[
`ou=HR,ou=Employees,ou=People`,
`ou=IT,ou=Employees,ou=People`,
`ou=Video,ou=Employees,ou=People`,
`ou=HR1,ou=HR,ou=Employees,ou=People` ,
`ou=aHR1,ou=HR,ou=Employees,ou=People` ,`ou=HR2,ou=HR1,ou=HR,ou=Employees,ou=People`,
]


into multi-dimensional like this
enter image description here

Answer Source

This code will give the desired out put.

$array = [
'ou=HR,ou=Employees,ou=People',
'ou=IT,ou=Employees,ou=People',
'ou=Video,ou=Employees,ou=People',
'ou=HR1,ou=HR,ou=Employees,ou=People',
'ou=aHR1,ou=HR,ou=Employees,ou=People',
'ou=HR2,ou=HR1,ou=HR,ou=Employees,ou=People',
];

foreach($array as $value){
    // explode string to array 
    $split_array = array_reverse(explode(',ou=',",".$value));
    // remove the empty element
    array_pop($split_array);
    // defing varaible with empty
    $value = '';
    // a php variable as string
    $string='$md';
    // loop the array
    foreach($split_array as $index => $key){   
        // append all the values as key to string
        $string.="['$key']";
     }
     // append empty value to string
     $string.= '=$value;';
     // Evaluate a string as PHP code
     eval($string);
}
 print_r($md); 

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Out put:

 Array
(
    [People] => Array
        (
            [Employees] => Array
                (
                    [HR] => Array
                        (
                            [HR1] => Array
                                (
                                    [HR2] => Array
                                        (
                                        )

                                )

                            [aHR1] => Array
                                (
                                )

                        )

                    [IT] => Array
                        (
                        )

                    [Video] => Array
                        (
                        )

                )

        )

)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download