2017-06-22 3 views
1

マルチ次元PHPに私の配列を変換することができ、私は私の配列は以下のようになりたい多次元配列はどのように私はこれが私の現在の配列です

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

答えて

1

が)あなたは(array_chunk使用することができますされ、live demo

array_chunk($array, 3, true); 
0

単にあなたは、すべてのサブ要素を保存するために補助変数を使用することができます。

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

私はあなたが本当のとは思わないあなたは出力テーブルに "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; 
} 
関連する問題