PHP多维数组键崩溃

时间:2013-05-21 15:42:46

标签: php multidimensional-array httprequest multipartform-data

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

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

3 个答案:

答案 0 :(得分: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"

}

答案 1 :(得分: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"
}

答案 2 :(得分: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);

我希望这会有所帮助。