现在我有一个数组有一些信息,我需要从它创建一个表.例如
Student{ [Address]{ [StreetAddress] =>"Some Street" [StreetName] => "Some Name" } [Marks1] => 100 [Marks2] => 50 }
Student_Address_StreetAddress Student_Address_StreetName Student_Marks1 Student_Marks2
它应该是递归的,所以从数组的任何深度,它可以创建我的格式的字符串.
您可以使用标准PHP库(
SPL)中的
RecursiveArrayIterator和
RecursiveIteratorIterator(以递归方式遍历数组),使此作业相对无痛.
$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);
上面的例子输出如下:
array ( 0 => 'Student_Address_StreetAddress',1 => 'Student_Address_StreetName',2 => 'Student_Marks1',3 => 'Student_Marks2',)