Get array's key recursively and create underscore separated string

后端 未结 5 755
走了就别回头了
走了就别回头了 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:26

    Something like this works:

     array (
         'Address' => array (
            'StreetAddress' => 'Some Street',
            'StreetName' => 'Some Name',
         ),
        'Marks1' => array(),
        'Marks2' => '50', 
      ),
    );
    
    $result = array();
    
    function dfs($data, $prefix = "") {
       global $result;
    
       if (is_array($data) && !empty($data)) {
          foreach ($data as $key => $value) {
            dfs($value, "{$prefix}_{$key}");
          }
       } else {
          $result[substr($prefix, 1)] = $data;
       }
    }
    
    dfs($arr);
    var_dump($result);
    
    ?>
    

    This prints:

    array(4) {
      ["Student_Address_StreetAddress"] => string(11) "Some Street"
      ["Student_Address_StreetName"] => string(9) "Some Name"
      ["Student_Marks1"] => array(0) {}
      ["Student_Marks2"] => string(2) "50"
    }
    

提交回复
热议问题