拼合多维数组串联键 [英] Flatten multidimensional array concatenating keys

查看:135
本文介绍了拼合多维数组串联键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1882894/php-convert-nested-array-to-single-array-while-concatenating-keys\">PHP转换嵌套数组单一阵列中,同时串联钥匙?结果
  <一href=\"http://stackoverflow.com/questions/2749398/get-arrays-key-recursively-and-create-underscore-seperated-string\">Get阵列的主要递归并创建下划线分隔字符串

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

Please, read the whole question before answering.

我有这样的多维数组:

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

我想把它压平,转化为:

I want it flatten, transformed into:

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

重要提示


  • 键是的非常对我很重要。我希望他们串联,用句点分隔。

  • The keys are very important to me. I want them concatenated, separated by periods.

它应该与任何级别的嵌套工作。

It should work with any level of nesting.

感谢您!

推荐答案

感谢所有给定的答案。

我已经在下面,这是一个改进版本转化它。它消除了根preFIX的需要,并不需要使用引用,这是更清洁的阅读,它有一个更好的名字:

I have transformed it in the following, which is an improved version. It eliminates the need of a root prefix, does not need to use references, it is cleaner to read, and it has a better name:

function array_flat($array, $prefix = '')
{
    $result = array();

    foreach ($array as $key => $value)
    {
        $new_key = $prefix . (empty($prefix) ? '' : '.') . $key;

        if (is_array($value))
        {
            $result = array_merge($result, array_flat($value, $new_key));
        }
        else
        {
            $result[$new_key] = $value;
        }
    }

    return $result;
}

这篇关于拼合多维数组串联键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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