【问题标题】:Post Array into array array in php在php中将数组发布到数组数组中
【发布时间】:2015-06-12 22:45:03
【问题描述】:

我想将我的帖子数组放入数组数组中。我有以下表单(此表单在 foreach 循环内),它将发布如下数组数据:

<input type="hidden" name="cl[]" value="">
<input type="hidden" name="cd[]" value="">

当在 firebug 中查看时,post 数组包含:

cl[]    4
cl[]    4
cd[]    John
cd[]    Shaw

我希望这些值合二为一,如下所示:

$allData = array(
    array(
        'cl' => 4,
        'cd' => 'John',
    ),
    array(
        'cl' => 4,
        'cd' => 'Shaw',
    )
);

请帮忙。

【问题讨论】:

  • 这些输入元素是如何呈现的?它们是动态的吗? (添加新行按钮)或者这个结构是静态的? (html 表单是硬编码的)

标签: php arrays forms post


【解决方案1】:

为了方便访问命名数组(可选)

<input type="text" name="data[cl][]" />
<input type="text" name="data[cd][]" />
<input type="text" name="data[cl][]" />
<input type="text" name="data[cd][]" />

双 foreach 循环:

foreach($_POST['data'] as $key => $row) {
        foreach($row as $subkey => $values) {
                $array[$subkey][$key]   =   $values;
            }
    }

 print_r($array); ?>

给你:

Array
(
    [0] => Array
        (
            [cl] => val1
            [cd] => val2
        )

    [1] => Array
        (
            [cl] => val3
            [cd] => val4
        )

)

【讨论】:

  • 你真的拯救了我的一天。工作正常。
【解决方案2】:
$cl[] =   4;
$cl[]  =  4;
$cd[]   = 'John';
$cd[]    ='Shaw';
if (!empty($cl) && !empty($cd)) {
    $count = count($cl);
    for ($i = 0; $i < $count; $i++) {
        $newArr[] = array('c1' => $cl[$i], 'cd' => $cd[$i]);
    }
}
print_r($newArr);

【讨论】:

  • for 循环比我已经使用过的 foreach 快。我不认为有任何修改可以加快速度。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 2015-07-09
  • 2013-04-09
  • 2011-03-22
相关资源
最近更新 更多