php 扁平化多维数组连接键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9546181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:05:09  来源:igfitidea点击:

Flatten multidimensional array concatenating keys

phparraysmultidimensional-arrayflatten

提问by J. Bruni

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

可能的重复:
PHP 在连接键时将嵌套数组转换为单个数组?
递归获取数组的键并创建下划线分隔的字符串

Please, read the whole question before answering.

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

I have this multidimensional array:

我有这个多维数组:

$data = array(
    'user' => array(
        'email'   => '[email protected]',
        'name'    => 'Super User',
        'address' => array(
            'billing' => 'Street 1',
            'delivery' => 'Street 2'
        )
    ),
    'post' => 'Hello, World!'
);

I want it flatten, transformed into:

我想让它变平,变成:

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

Important:

重要

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

  • It should work with any level of nesting.

  • 钥匙对我来说重要。我希望它们连接起来,用句点分隔。

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

Thank you!

谢谢!

采纳答案by J. Bruni

Thanks for all the given answers.

感谢所有给出的答案。

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;
}

回答by Felix Kling

Something like this should work:

这样的事情应该工作:

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

演示

回答by Basti

Try this

尝试这个

<?php

$data = array(
    'user' => array(
        'email'   => '[email protected]',
        'name'    => 'Super User',
        'address' => array(
            'billing' => 'Street 1',
            'delivery' => 'Street 2'
        )
    ),
    'post' => 'Hello, World!'
);

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

var_dump(prefixKey('', $data));

?>

Outputs

输出

array
  'user.email' => string '[email protected]' (length=16)
  'user.name' => string 'Super User' (length=10)
  'user.address.billing' => string 'Street 1' (length=8)
  'user.address.delivery' => string 'Street 2' (length=8)
  'post' => string 'Hello, World!' (length=13)

回答by scibuff

Use recursion such as this:

使用递归,例如:

function process_data( $data, $parent_key ){

    if ( ! is_array( $data ) ){
        return $data;
    }

    $flattened_array = array();
    foreach( $data as $key => $item ){
        $flattened_key = $parent_key . '.' . $key;
        $flattened_array[ $flattened_key ] = process_data( $item, $flattened_key );
    }

    return $flattened_array;

}

回答by Joseph

test this out here

在这里测试一下

i passed by reference so no need for returns. just hand over the array storage.

我是通过引用传递的,所以不需要返回。只需交出阵列存储。

$store = array();

function flatten($array,&$storage,$parentKey = ''){
    foreach($array as $key => $value){
    $itemKey = (($parentKey)? $parentKey.'.':'').$key;
        if(is_array($value)){
            flatten($value,$storage,$itemKey);
        } else {
            $storage[$itemKey] = $value;
        }
    }   
}

flatten($data,$store);
var_dump($store);