tags:

views:

37

answers:

1

Assume I have arrays like:

$arr['foo']['bar']['test'] = 'value';
$arr['noo']['boo'] = 'value';
$arr['goo'] = 'value';
$arr['hi'][] = 'value'; // $arr['hi'][0]
$arr['hi'][] = 'value2'; // $arr['hi'][1]

I need to convert this, to:

$arr['foo[bar][test]'] = 'value';
$arr['noo[boo]'] = 'value';
$arr['goo'] = 'value';
$arr['hi[0]'] = 'value';
$arr['hi[1]'] = 'value2';

I have tried writing a recursive function, though it seems I have a lack of logic for it. I appreciate help writing this code.

Many people keep asking why I need this? Well.. it is for my form class and I find it pretty useful there.

+1  A: 

Based on first comment here: http://php.net/manual/en/function.array-values.php

<?php

$arr['foo']['bar']['test'] = 'value1';
$arr['noo']['boo'] = 'value2';
$arr['goo'] = 'value3';
$arr['hi'][] = 'value4'; // $arr['hi'][0]
$arr['hi'][] = 'value5'; // $arr['hi'][1]

function array_flatten($a,$f=array(), $prefix = "") {
  if(!$a||!is_array($a))return '';
  foreach($a as $key=>$value) {
    if(is_array($value)) {  
      $pref = ($prefix === "") ? $key : $prefix . "[$key]";
      $f = array_flatten($value,$f, $pref);
    } else {
      $pref = ($prefix === "") ? $key : $prefix . "[$key]";        
      $f[ $pref ] = $value;
    }  
  }
  return $f;
}

var_dump(array_flatten($arr));

/*

Expected output:

$arr['foo[bar][test]'] = 'value1';
$arr['noo[boo]'] = 'value2';
$arr['goo'] = 'value3';
$arr['hi[0]'] = 'value4';
$arr['hi[1]'] = 'value5';

My output:

array(5) {
  ["foo[bar][test]"]=>
  string(6) "value1"
  ["noo[boo]"]=>
  string(6) "value2"
  ["goo"]=>
  string(6) "value3"
  ["hi[0]"]=>
  string(6) "value4"
  ["hi[1]"]=>
  string(6) "value5"
}

*/
?>
MartyIX