1

I need to flatten an array while making sure that there are no duplicate keys.

For instance let's say I have this:

$arr = array(
    $foo = array(
        'donuts' => array(
                'name' => 'lionel ritchie',
                'animal' => 'manatee',
            )
    )
);

I need a flattened array that looks like this:

$arr = array(
     'donuts name' => 'lionel ritchie',
     'donuts animal' => 'manatee',
);

It needs to work even if we have more than 1 parent keys.

I have the following code, but I am not sure I can work with this.

foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){
   $array1c[$k] = $v;
}
Barry
  • 3,303
  • 7
  • 23
  • 42
dms
  • 129
  • 1
  • 1
  • 8

1 Answers1

1

It's very simple to do, just make it like this:

$arr = array(
    $foo = array(
        'donuts' => array(
                'name' => 'lionel ritchie',
                'animal' => 'manatee',
            )
    )
);

// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
      // Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
      array_splice($foo, array_search($findex, array_keys($foo)), 1); 
      foreach($child as $index => $value) {
            // Adds an array element for every child
            $foo[$findex.' '.$index] = $value;
      }
}

Result of var_dump($foo); will be:

array(2) {
  ["donuts name"]=>
  string(14) "lionel ritchie"
  ["donuts animal"]=>
  string(7) "manatee"
}

Just try :)

SyncroIT
  • 1,510
  • 1
  • 14
  • 26