递归获取数组的键并创建下划线分隔的字符串 [英] Get array's key recursively and create underscore separated string

查看:65
本文介绍了递归获取数组的键并创建下划线分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我得到了一个包含某种信息的数组,我需要从中创建一个表.例如

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] =>"Some Street"
              [StreetName] => "Some Name"
      }
      [Marks1] => 100
      [Marks2] => 50
    }

现在,我想创建数据库表,其中包含字段名称为:

Now I want to create database table like which contain the fields name as :

Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2

它应该是递归的,以便从数组的任何深度可以创建我格式的字符串.

It should be recursive so from any depth of array it can create the string in my format.

推荐答案

您可以使用 RecursiveArrayIterator 和<来自标准PHP库(

You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
    // Build long key name based on parent keys
    for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
        $key = $iterator->getSubIterator($i)->key() . '_' . $key;
    }
    $keys[] = $key;
}
var_export($keys);

上面的示例输出如下内容:

The above example outputs something like:

array (
  0 => 'Student_Address_StreetAddress',
  1 => 'Student_Address_StreetName',
  2 => 'Student_Marks1',
  3 => 'Student_Marks2',
)

这篇关于递归获取数组的键并创建下划线分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆