1

我想折叠一个多维数组,以便

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

会崩溃到

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

我想要做的是将multipart/form-data $_POST数组恢复到原始请求正文,如下所示:

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

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

bar
------WebKitFormBoundaryxiOccKlMg4Al6VbH--
4

3 回答 3

0

试试这个代码:

$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();

它输出:

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

}
于 2013-05-21T15:52:14.693 回答
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);

var_dump()'ed 时的输出:

array(2) {
  ["first[second][0]"]=>
  string(3) "foo"
  ["first[second][1]"]=>
  string(3) "bar"
}
于 2013-05-21T15:52:22.320 回答
0

那这个呢?

$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);

我希望这有帮助。

于 2013-05-21T15:55:33.113 回答