vote up 0 vote down star

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?

flag

2 Answers

vote up 4 vote down check

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);
link|flag
+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 2 days ago
good example. I like the idea of passing the output array by reference. – GSto 2 days ago
vote up 0 vote down

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

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.