在PHP中将$ _POST安排到多维数组

时间:2018-05-31 09:51:24

标签: php multidimensional-array

我在提交表单时有一个表单,如果打印$ _POST我将获得如下输出

    [type] =>'new',
[class] =>'10',
[div] =>c,
[id_228] => 228,
[title_228]=> First,
[colour_228]=> red,
[id_229] => 229,
[title_229]=> second,
[colour_229]=> blue,
[id_230] => 230,
[title_230]=> third,
[colour_230]=> yellow,
[id_231] => 231,
[title_231]=> fourth,
[colour_231]=> orange,

现在我必须将此输出存储到结果数组中。请参阅结果数组

result_array[1]=array("Title", 'Color')

所以在这个结果数组中我必须像这样添加$ _POST

result_array[228]=array("First","red")
result_array[229]=array("Second","blue")
result_array[230]=array("Third","yellow")
result_array[231]=array("Fourth","red")

请帮忙。

3 个答案:

答案 0 :(得分:2)

你必须循环它并准备一个新阵列。

$result = array();
foreach ($_POST as $key => $value) {
    list($title, $key) = explode('_', $key);
    if (!is_array($result[$key])) $result[$key] = array();

    $result[$key][$title] = $value;
}

var_dump($result);

希望这有帮助。

答案 1 :(得分:2)

第一步应该是从这些数据中创建一个正确的数组: https://3v4l.org/r0HZ9     

$post = [
    'id_228' => 228,
    'title_228' => "First",
    'colour_228' => 'red',

    'id_229' => 228,
    'title_229' => "Second",
    'colour_229' => 'blue'];


// Transform data into a proper format
$resultArray = [];
foreach($post as $key => $val) {
    $key = explode('_',$key);
    $resultArray[$key[1]][$key[0]] = $val;
}

// Now do whatever you want to do 
var_dump($resultArray);

现在您可以添加更多逻辑...如果您想要所提议格式的数据,您可以

$result = [];
foreach($resultArray as $item) { 
    $result[] = [$item['title'], $item['colour']];
}

https://3v4l.org/WC2B0

修改 自从你添加了

[type] =>'new',
[class] =>'10',
[div] =>c,

您可能想要创建一个应添加的允许字段列表,可能类似于:

// Transform data into a proper format
$resultArray = [];
$allowedFields = ['id', 'title', 'colour'];
foreach($post as $key => $val) {
    $key = explode('_',$key);
    if(in_array($key[0], $allowedFields)) {
        $resultArray[$key[1]][$key[0]] = $val;
    }
}

https://3v4l.org/NQGfa

答案 2 :(得分:2)

$arr= ["id_228" => 228, "title_228" => "First",
"colour_228"=> "red",
"id_229" => 229,
"title_229"=> "second",
"colour_229"=> "blue",
"id_230" => 230,
"title_230"=> "third",
"colour_230"=> "yellow",
"id_231" => 231,
"title_231"=> "fourth",
"colour_231"=> "orange" ];

foreach($arr as $key => $value) {
    $d = explode( '_', $key );
    if(true == is_numeric( $value)) {
        continue;
    }
    $c[$d[1]][]= $value ;
}
print_r($c);

Out put

Array
(
    [228] => Array
        (
            [0] => First
            [1] => red
        )

    [229] => Array
        (
            [0] => second
            [1] => blue
        )

    [230] => Array
        (
            [0] => third
            [1] => yellow
        )

    [231] => Array
        (
            [0] => fourth
            [1] => orange
        )

)