Get array's key recursively and create underscore separated string

后端 未结 5 756
走了就别回头了
走了就别回头了 2020-11-29 09:06

Right now i got an array which has some sort of information and i need to create a table from it. e.g.

Student{
      [Address]{
              [StreetAddress         


        
5条回答
  •  感情败类
    2020-11-29 09:35

    (Working on it, here is the array to save the trouble):

    $arr = array
    (
        'Student' => array
        (
            'Address' => array
            (
                'StreetAddress' => 'Some Street',
                'StreetName' => 'Some Name',
            ),
            'Marks1' => '100',
            'Marks2' => '50',
        ),
    );
    

    Here it is, using a modified version of @polygenelubricants code:

    function dfs($array, $parent = null)
    {
        static $result = array();
    
        if (is_array($array) * count($array) > 0)
        {
            foreach ($array as $key => $value)
            {
                dfs($value, $parent . '_' . $key);
            }
        }
    
        else
        {
            $result[] = ltrim($parent, '_');
        }
    
        return $result;
    }
    
    echo '
    ';
    print_r(dfs($arr));
    echo '
    ';

    Outputs:

    Array
    (
        [0] => Student_Address_StreetAddress
        [1] => Student_Address_StreetName
        [2] => Student_Marks1
        [3] => Student_Marks2
    )
    

提交回复
热议问题