【问题标题】:How can i convert my array into Multi-dimentional PHP如何将我的数组转换为多维 PHP
【发布时间】:2017-06-22 07:35:58
【问题描述】:

这是我当前的数组,我想把这个数组转换成多维数组

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++;
}

【问题讨论】:

    标签: php arrays multidimensional-array associative-array


    【解决方案1】:

    可以使用array_chunk(),live demo

    array_chunk($array, 3, true);
    

    【讨论】:

      【解决方案2】:

      只需使用辅助变量来保存所有子元素:

      $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++;
      }
      

      【讨论】:

        【解决方案3】:

        我不认为你真的想要输出表中的“question1”。我想你会想要“问题”。但如果你想要“question1”等,将“$tmp[$key]”行更改为“$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;
        }
        

        【讨论】:

          猜你喜欢
          • 2015-04-04
          • 1970-01-01
          • 1970-01-01
          • 2015-11-17
          • 2011-12-09
          • 1970-01-01
          • 2012-06-05
          • 2019-09-22
          • 1970-01-01
          相关资源
          最近更新 更多