将Simple数组转换为下面的结果数组

时间:2015-05-08 13:26:01

标签: php arrays

我正在使用php

下面是我的数组

Array
(
    [0] => Q .
    [1] => What are the factors of x2+2x+1?
    [2] => A .
    [3] => (x+1)
    [4] => B .
    [5] => (x-1)
    [6] => C .
    [7] => (2x+1)
    [8] => D .
    [9] => (2x-1)
    [10] => S .
    [11] => (x+1)
    [12] => M.
    [13] => 20
    [14] => Q .
    [15] => Test  are the factors of x2-2x+1?
    [16] => A .
    [17] => (x+1)
    [18] => B .
    [19] => (x-1)
    [20] => C .
    [21] => (2x+1)
    [22] => D .
    [23] => (2x-1)
    [24] => S .
    [25] => (x-1)
    [26] => M.
    [27] => 5
)

我想要结果

Array
(
    [0] => Array
        (
            [question] => What are the factors of x2+2x+1?
            [A.] => (x+1)
            [B.] => (x-1)
            [C.] => (2x+1)
            [D.] => (2x-1)
            [S.] => (x+1)
            [M.] => 20
        )

 [0] => Array
        (
            [question] => TEST What are the factors of x2+2x+1?
            [A.] => (x+1)
            [B.] => (x-1)
            [C.] => (2x+1)
            [D.] => (2x-1)
            [S.] => (x+1)
            [M.] => 
        )

)

请告知。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

$array = Array
(
    0 =>  "Q .",
    1 =>  "What are the factors of x2+2x+1?",
    2 =>  "A .",
    3 =>  "(x+1)",
    4 =>  "B .",
    5 =>  "(x-1)",
    6 =>  "C .",
    7 =>  "(2x+1)",
    8 =>  "D .",
    9 =>  "(2x-1)",
    10 => "S ." ,
    11 => "(x+1)" ,
    12 => "M." ,
    13 => "20" ,
    14 => "Q ." ,
    15 => "Test  are the factors of x2-2x+1?" ,
    16 => "A ." ,
    17 => "(x+1)" ,
    18 => "B ." ,
    19 => "(x-1)" ,
    20 => "C ." ,
    21 => "(2x+1)" ,
    22 => "D ." ,
    23 => "(2x-1)" ,
    24 => "S ." ,
    25 => "(x-1)" ,
    26 => "M." ,
    27 => "5" ,
);

$keys = array(
    'question','A. ','B. ','C. ','D. ','S. ','M. '
);

$result = array_map(
    function($q) use ($keys) {
        return array_combine($keys, $q);  // 4. make our keys the keys of each resulting array
    },
    array_chunk(
        array_map(
            function($a){
                return $a[1];      // 2. select only the 2nd part of the chunk
            },
            array_chunk($array, 2) // 1. split initial array into chunks of 2
        )
    ,7)                            // 3. split it into chunks of 7
);