views:

427

answers:

3

Here is an example array:

 $foo = array(
           'employer' => array(
                    'name' => 'Foobar Inc',
                    'phone' => '555-555-5555'
                     ),
           'employee' => array(
                    'name' => 'John Doe',
                    'phone' => '555-555-5556',
                    'address' => array(
                           'state' => 'California',
                           'zip' => '90210'
                    ),
           'modified' => '2009-12-01',
         );

And I would like to get a result like this:

$fooCompressed = array(
             'employer_name' => 'Foobar Inc',
             'employer_phone' => '555-555-5555',
             'employee_name' => 'John Doe',
             'employee_phone' => '555-555-5556'
             'employee_address_state' => 'California',
             'employee_address_zip' => '90210',
             'modified' => '2009-12-01'
             )

how would I go about writing a recursive function to handle this?

+4  A: 

Something like this:

function makeNonNestedRecursive(array &$out, $key, array $in){
    foreach($in as $k=>$v){
     if(is_array($v)){
         makeNonNestedRecursive($out, $key . $k . '_', $v);
     }else{
            $out[$key . $k] = $v;
     }
    }
}

function makeNonNested(array $in){
    $out = array();
    makeNonNestedRecursive($out, '', $in);
    return $out;
}

// Example
$fooCompressed = makeNonNested($foo);
VDVLeon
+1 This is pretty close to what I'd do. Because the keys are being modified, there is no built-in function that will do it for you, and you definitely need recursion to drill down through any sub-values that are also arrays.
zombat
good example. I like the idea of passing the output array by reference.
GSto
A: 

This works, and allows you to specify a top-level prefix via the second param

function flatten_array($array, $prefix = null) {
  if ($prefix) $prefix .= '_';

  $items = array();

  foreach ($array as $key => $value) {
    if (is_array($value))
      $items = array_merge($items,  flatten_array($value, $prefix . $key));
    else
      $items[$prefix . $key] = $value;
  }

  return $items;
}
meagar
A: 

you have solved my problem...thanks yaar

anjana