JS数组合并为一个数组

时间:2018-04-09 17:34:17

标签: php arrays

我使用serialisedArray跟随js数组 -

Array
(
    [0] => Array
        (
            [name] => sub_maintenance_template[1][maintenance_location_id]
            [value] => 54321
        )

    [1] => Array
        (
            [name] => sub_maintenance_template[1][maintenance_problem_id]
            [value] => 65432
        )

    [2] => Array
        (
            [name] => sub_maintenance_template[1][maintenance_priority_id]
            [value] => 76896
        )

    [3] => Array
        (
            [name] => sub_maintenance_template[1][description]
            [value] => sample description
        )
)

预期数组 -

[sub_maintenance_template] => Array (
    [1] =>
        (
            [maintenance_location_id]=> 54321
            [maintenance_problem_id]=> 65432
            [maintenance_priority_id]=>76896
            [description]=> sample description
        )
)

我试过这样 -

foreach( $tableData as $key => $value ) {
        echo $key;
        $newArray['sub_maintenance_template'][3][] = $value['name'];
        $newArray['sub_maintenance_template'][3][] = $value['value'];
    } 

即使我通过foreach迭代它但未能获得所需的输出。有没有办法得到理想的?

1 个答案:

答案 0 :(得分:1)

最好将它们作为GET或POST中的实际数组传递,但由于name中的字符串是如何在URL查询字符串中传递数组,因此可以使用parse_str:< / p>

foreach($array as $values) {
    parse_str("{$values['name']} = {$values['value']}", $result);
}
print_r($result);

或者另一种方式;提取并构建键/值对以构建查询字符串,然后解析它:

parse_str(http_build_query(array_column($array, 'value', 'name')), $result);
print_r($result);