1

I'd like to collapse a multidimensional array so that

$arr = array(
    'first' => array(
        'second' => array(
            0 => 'foo',
            1 => 'bar'
        )
    )
);

would collapse to

$arr = array(
    'first[second][0]' => 'foo',
    'first[second][1]' => 'bar'
);

What I'm trying to do is to restore a multipart/form-data $_POST array to the original request body, like this:

------WebKitFormBoundaryxiOccKlMg4Al6VbH
Content-Disposition: form-data; name="first[second][0]"

foo
------WebKitFormBoundaryxiOccKlMg4Al6VbH
Content-Disposition: form-data; name="first[second][1]"

bar
------WebKitFormBoundaryxiOccKlMg4Al6VbH--
Giovanni Lovato
  • 2,183
  • 2
  • 29
  • 53
  • Extend the example, by this example your question is vague! Also put your works and what you have done so far. – SAVAFA May 21 '13 at 15:45
  • [Possible duplicate](http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php) – Jordan Doyle May 21 '13 at 16:16

3 Answers3

0

Try this code:

$arr = array(
    'first' => array(
        'second' => array(
            0 => 'foo',
            1 => 'bar'
        )
    )
);
$result = array();
function processLevel(&$result, $source, $previous_key = null) {
    foreach ($source as $k => $value) {
        $key = $previous_key ? "{$previous_key}[{$k}]" : $k;
        if (!is_array($value)) {
            $result[$key] = $value;
        } else {
            processLevel($result, $value, $key);
        }
    }
}
processLevel($result, $arr);
var_dump($result);
die();

It outputs:

array(2) {
  ["first[second][0]"] => string(3) "foo"
  ["first[second][1]"] => string(3) "bar"

}
Bogdan Burym
  • 5,482
  • 2
  • 27
  • 46
0
function collapseArray ($array, $tree = array(), $step = 0) {
    $result = array();
    foreach ($array as $key => $val) {
        $tree[$step] = $key;
        if (is_scalar($val)) {
            $first = array_shift($tree);
            $result["{$first}[".implode("][", $tree)."]"] = $val;
            array_unshift($tree, $first);
        } else {
            $result += collapseArray($val, $tree, $step + 1);
        }
    }
    return $result;
}

$arr = array(
    'first' => array(
        'second' => array(
            0 => 'foo',
            1 => 'bar'
        )
    )
);

$newArray = collapseArray($arr);

Outputs when var_dump()'ed:

array(2) {
  ["first[second][0]"]=>
  string(3) "foo"
  ["first[second][1]"]=>
  string(3) "bar"
}
bwoebi
  • 23,637
  • 5
  • 58
  • 79
0

what about this?

$arr = array(
    'first' => array(
        'second' => array(
            0 => 'foo',
            1 => 'bar'
        )
    )
);
$newArray=array();
foreach($arr['first']['second'] as $k=>$v)
{
    $newArray['first[second]['.$k.']']=$v;
}

var_dump($arr);
var_dump($newArray);

I hope this helps.

Ruslan Polutsygan
  • 4,401
  • 2
  • 26
  • 37