0
$arr = [
    'name' => 'John',
    'access' => '1',
    'address' => [
        'line_1' => '10',
        'line_2' => 'example street',
    ],
]

How can I flatten this example array (or turn it into a collection) without losing keys, I've tried to use collect and flatten but this loses the keys.

I'm expecting this:

$arr = [
    'name' => 'John',
    'access' => '1',
    'line_1' => '10',
    'line_2' => 'example street',
 ]
Rahul
  • 18,271
  • 7
  • 41
  • 60
panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

4

You can try like this by using core iterator functions,

$temp = [];
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($it as $k => $v) {
  $temp[$k] = $v;
}
print_r($temp);

RecursiveIteratorIterator - Can be used to iterate through recursive iterators.

RecursiveArrayIterator - This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the ArrayIterator. Additionally it is possible to iterate over the current iterator entry.

Output

Array
(
    [name] => John
    [access] => 1
    [line_1] => 10
    [line_2] => example street
)

Demo.

Rahul
  • 18,271
  • 7
  • 41
  • 60
  • I don't currently have this problem but Very nice, idk why i don't know this but usually i do the recursivity func manually, but this is satisfying, thanks – Achraf Khouadja Mar 08 '19 at 13:11
0

I think @Rahul Meshram's solution is better, but you can try this one, too.

Try

    <?php

$arr = [
    'name' => 'John',
    'access' => '1',
    'address' => [
        'line_1' => '10',
        'line_2' => 'example street',
    ],
];

$newArray = [];

foreach ($arr as $k1 => $v1){

    if(is_array($v1) && count($v1) > 0){
        foreach ($v1 as $k2 => $v2){
            $newArray[$k2] = $v2 ;
        }
    }else {
        $newArray[$k1] = $v1 ;
    }
}

print_r($newArray);
ydlgr
  • 57
  • 1
  • 6