user3076307
user3076307

Reputation:

How can i convert my array into Multi-dimentional PHP

This is my current array, I want to convert this array into multi-dimensional 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
)

I want my array to be like this below. how can achieve this, any suggestions?

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
       )
 )

Here is my code

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

Upvotes: 1

Views: 47

Answers (3)

LF-DevJourney
LF-DevJourney

Reputation: 28529

You can use array_chunk(), live demo

array_chunk($array, 3, true);

Upvotes: 1

ElChupacabra
ElChupacabra

Reputation: 1091

I don't think you really want "question1" in output table. I think you will want "question" instead. But if you want "question1" etc. change the line "$tmp[$key]" to "$tmp[$key.$i]". The "for" loop should be also changed "in real life" because you will have more keys I guess but here is the code that gives you good start :)

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

Upvotes: 0

Alberto
Alberto

Reputation: 1489

Simply you can use an aux variable to save all subelements:

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

Upvotes: 0

Related Questions