PHP多维数组键折叠



我想折叠一个多维数组,这样

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

试试这个代码:

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

这个怎么样?

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

我希望这能有所帮助。

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"
}

相关内容

  • 没有找到相关文章

最新更新