php - 展平多维数组连接键

标签 php arrays multidimensional-array flatten

<分区>

Possible Duplicate:
PHP convert nested array to single array while concatenating keys?
Get array's key recursively and create underscore seperated string

请在回答之前阅读整个问题。

我有这个多维数组:

$data = array(
    'user' => array(
        'email'   => 'user@example.com',
        'name'    => 'Super User',
        'address' => array(
            'billing' => 'Street 1',
            'delivery' => 'Street 2'
        )
    ),
    'post' => 'Hello, World!'
);

我想让它变平,变成:

$data = array(
    'user.email' => 'user@example.com',
    'user.name'  => 'Super User',
    'user.address.billing'  => 'Street 1',
    'user.address.delivery' => 'Street 2',
    'post'       => 'Hello, World!'
);

重要:

  • key 对我来说非常重要。我希望将它们串联起来,用句点分隔。

  • 它应该适用于任何级别的嵌套。

谢谢!

最佳答案

这样的事情应该可以工作:

function flatten($array, $prefix = '') {
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + flatten($value, $prefix . $key . '.');
        }
        else {
            $result[$prefix . $key] = $value;
        }
    }
    return $result;
}

DEMO

关于php - 展平多维数组连接键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9546181/

相关文章:

在 Windows 资源管理器中打开时,PHP .zip 文件下载错误

javascript - REST API 与直接访问代码

javascript - 按顺序将 HTML 表数据保存在 Excel 文件中

ruby-on-rails - Rails 4 - 如何在 postgres 上存储数组

php - 在多维数组中搜索键然后使用 PHP 更改值

c++ - 返回 0 的 Double 二维数组

PHP imap_search 未检测到 gmail 收件箱中的所有邮件

php - 如何从现有 Eclipse PDT 中删除 Zend Studio 组件?

java - 我需要帮助在 java 中声明数组

php - 如何使用php从mysql查询直接创建多维数组?