-5

i am using $_POST for getting all input values and it generates an array like:

[seen1] => 1
[flag1] => 0
[time1] => 275
[qtsnums1] => 17
[seen2] => 0
[flag2] => 0
[time2] => 0
[qtsnums2] => 11
[seen3] => 0
[flag3] => 0
[time3] => 0
[qtsnums3] => 9
[seen4] => 0
[flag4] => 0
[time4] => 0
[qtsnums4] => 5
[seen5] => 0
[flag5] => 0
[time5] => 0
[qtsnums5] => 10

i want to split:

[seen1] => 1
[flag1] => 0
[time1] => 275
[qtsnums1] => 17

and insert in 1 variable, how to do this?

4

3 回答 3

3

array_chunk将帮助您拆分数组:

$new = array_chunk($_POST, 4, true) ; //Do not forget to use TRUE to save indices

$desired_result = $new[0] ;
var_dump($desired_result) ;
于 2013-07-04T06:44:52.543 回答
2

假设您的输入数组名为$input,您可以使用以下命令创建新数组:

$output = array();
$wantedKeys = array('seen1', 'flag1', 'time1', 'qtsnums1');
foreach ($wantedKeys as $key)
{
    $output[$key] = $input[$key];
}
print_r($output);

要获取包含前四个键的列表,无论它们如何命名:

$wantedKeys = array_slice(array_keys($input), 0, 4);

您也可以使用上述array_chunk. 如果你想摆脱单线,你可以这样做:

$output = current(array_chunk($input, 4, true));

请注意,它会在较新版本的 PHP 中生成有关引用的警告。在这种情况下,您可以使用这个:

$output = array_chunk($input, 4, true)[0];

但是,这会在旧 PHP 上产生语法错误。

于 2013-07-04T06:44:07.760 回答
1

是的,如果您只需要前 4 个,array_slice() 就可以了。但下面是一个通用的,它将输入数组拆分为不同的块。

$array = array(
    'seen1' => 1,
    'flag1' => 0,
    'time1' => 3,
    'qtsnums1' => 4,
    'seen2' => 1,
    'flag2' => 0,
    'time2' => 3,
    'qtsnums2' => 4,
    'seen3' => 1,
    'flag3' => 0,
    'time3' => 3,
    'qtsnums3' => 4,
);

$new_array = array();

foreach($array as $key => $value){
    preg_match('/([^0-9]+)(\d+)/', $key, $matches);
    $new_array[$matches[2]][$matches[1]] = $value;
}
print_r($new_array);

输出将如下

Array
(
    [1] => Array
        (
            [seen] => 1
            [flag] => 0
            [time] => 3
            [qtsnums] => 4
        )

    [2] => Array
        (
            [seen] => 1
            [flag] => 0
            [time] => 3
            [qtsnums] => 4
        )

    [3] => Array
        (
            [seen] => 1
            [flag] => 0
            [time] => 3
            [qtsnums] => 4
        )

)

因此,给 $new_array[1] 将获得第一个块,而 $new_array[2] 将获得第二个块,依此类推。

于 2013-07-04T06:53:49.803 回答