递归获取数组的键并创建下划线分隔的字符串

Neh*_*hal 11 php arrays multidimensional-array

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

Student{
      [Address]{
              [StreetAddress] =>"Some Street"
              [StreetName] => "Some Name"
      }
      [Marks1] => 100
      [Marks2] => 50
    }
Run Code Online (Sandbox Code Playgroud)

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

Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
Run Code Online (Sandbox Code Playgroud)

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

sal*_*the 18

您可以使用RecursiveArrayIteratorRecursiveIteratorIterator(以递归方式迭代数组)从标准PHP库(SPL)中使此作业相对轻松.

$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);
Run Code Online (Sandbox Code Playgroud)

以上示例输出如下内容:

array (
  0 => 'Student_Address_StreetAddress',
  1 => 'Student_Address_StreetName',
  2 => 'Student_Marks1',
  3 => 'Student_Marks2',
)
Run Code Online (Sandbox Code Playgroud)


Ali*_*xel 8

(在它上面工作,这是节省麻烦的数组):

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

在这里,使用@polygenelubricants代码的修改版本:

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 '<pre>';
print_r(dfs($arr));
echo '</pre>';
Run Code Online (Sandbox Code Playgroud)

输出:

Array
(
    [0] => Student_Address_StreetAddress
    [1] => Student_Address_StreetName
    [2] => Student_Marks1
    [3] => Student_Marks2
)
Run Code Online (Sandbox Code Playgroud)