如何将我的数组转换为多维PHP

时间:2017-06-22 07:35:58

标签: php arrays multidimensional-array associative-array

这是我当前的数组,我想将这个数组转换为多维数组

Array
(
    [question1] => My question 1
    [options1] => My Option 1
    [answer1] => Answer 1 goes here
    [question2] =>  My question 2
    [options2] => My Option 2
    [answer2] => Answer 2 goes here
)

我希望我的数组如下所示。怎么能实现这个,有什么建议吗?

Array
(
    [0] => Array
        (
          [question1] => My question 1
          [options1] => My Option 1
          [answer1] => Answer 1 goes here
        )

    [1] => Array
       (
           [question2] =>  My question 2
           [options2] => My Option 2
           [answer2] => Answer 2 goes here
       )
 )

这是我的代码

$i=9;
$topicsArr=array();
$j = 1;
while ($row[$i]){
    $topicsArr['question' .$j] = $row[$i];
    $topicsArr['options' .$j] = $row[$i+1];
    $topicsArr['answer' .$j] = $row[$i+2];
    $i = $i +3;
    $j++;
}

3 个答案:

答案 0 :(得分:1)

您可以使用array_chunk(),live demo

array_chunk($array, 3, true);

答案 1 :(得分:0)

只需使用aux变量即可保存所有子元素:

$i=9;
$topicsArr=array();
$j = 1;
while ($row[$i]){
    $aux = array();
    $aux['question'] = $row[$i];
    $aux['options'] = $row[$i+1];
    $aux['answer'] = $row[$i+2];
    $topicsArr.push($aux);
    $i = $i +3;
    $j++;
}

答案 2 :(得分:0)

我不认为你真的想要"问题1"在输出表中。我想你会想要"问题"代替。但如果你想要"问题1"等改变线" $ tmp [$ key]" to" $ tmp [$ key。$ i]"。 " for"循环也应该在现实生活中改变"因为你会有更多的钥匙我猜这里是给你良好开端的代码:)

$input = [
    'question1' => 'My question 1',
    'options1' => 'My Option 1',
    'answer1' => 'Answer 1 goes here',
    'question2' => 'My question 2',
    'options2' => 'My Option 2',
    'answer2' => 'Answer 2 goes here'
];
$output = [];
for ($i=1; $i<=2; $i++) {
    $tmp = [];
    foreach (['question', 'options', 'answer'] as $key) {
        $tmp[$key] = $input[$key.$i];
    }
    $output[] = $tmp;
}