32

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

Please, read the whole question before answering.

I have this multidimensional array:

$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!'
);

Important:

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

  • It should work with any level of nesting.

Thank you!

Community
  • 1
  • 1
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
  • There are several similar questions, but I have not found a duplicate. – J. Bruni Mar 03 '12 at 12:35
  • 1
    Indeed, there are two duplicates. I didn't know when asking. Anyway, all answers to them (except meagar's one) are far inferior than the ones given here now... they are unnecessarily complicated (using iterators, globals, classes, and the like, when it can be as simple as we can see here). – J. Bruni Mar 03 '12 at 13:19

5 Answers5

76

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
24

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;
}
J. Bruni
  • 20,322
  • 12
  • 75
  • 92
9

Try this

<?php

$data = array(
    'user' => array(
        'email'   => 'user@example.com',
        '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 'user@example.com' (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)
Basti
  • 3,998
  • 1
  • 18
  • 21
3

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);
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

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;

}
scibuff
  • 13,377
  • 2
  • 27
  • 30