递归获取阵列的主要创造下划线分隔字符串 [英] Get array's key recursively and create underscore seperated string

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

问题描述

现在,我得到了它具有某种信息的数组,我需要从它创建一个表。例如。

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 和的 RecursiveIteratorIterator (数组到递归迭代)( SPL ),以使这项工作相对容易。

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天全站免登陆