Iterating on a multidimensional array

Asked

Viewed 198 times

0

<?php
$data = array();
//questoes de user 1
$data['rows']['questions'][1] = array(
    array('id' => 1, 'type' => 'radio', 'name' => "Onde fica ilha de Santiago"),
    array('id' => 2, 'type' => 'radio', 'name' => "Onde fica tarafal"),
    array('id' => 3, 'type' => 'boolean', 'name' => "Cidade velha é a capital de Cabo Verde"),

);
$data['rows']['aresponses'][1] = array(
    '1' => array(
        array('id' => 1, 'name' => "No barlavanto"),
        array('id' => 2, 'name' => "No sotavento"),
        array('id' => 3, 'name' => "No norte do arquipélago"),
    ),
    '2' => array(
        array('id' => 1, 'name' => "Na ilha do fogo"),
        array('id' => 2, 'name' => "Na ilha de santiago"),
        array('id' => 3, 'name' => "Na ilha de brava"),
    ),
    '3' => array(
        array('id' => 1, 'name' => "Verdairo"),
        array('id' => 2, 'name' => "Falso"),
    ),

);
?>

Relating each question to a list of response alternatives

Example:

>       Pergunta:  Onde fica ilha de Santiago
>               
>       Alternativa1:  No barlavanto
>       Alternativa2:  No sotavento
>       Alternativa2   No norte do arquipélago
  • Just take the [questions] ID and add after the [aresponses][1][{ID}], so does a foreach of each item.

1 answer

0

Friend, the index of the array that contains the alternatives needs to start at 0, as well as the indexes that contain the questions, so the iteration of the array between the questions and answers, will stay this way:

$data = array();
//questoes de user 1
$data['rows']['questions'][1] = array(
    array('id' => 1, 'type' => 'radio', 'name' => "Onde fica ilha de Santiago"),
    array('id' => 2, 'type' => 'radio', 'name' => "Onde fica tarafal"),
    array('id' => 3, 'type' => 'boolean', 'name' => "Cidade velha é a capital de Cabo Verde"),

);

$data['rows']['aresponses'][1] = array(
    0 => array(
        array('id' => 1, 'name' => "No barlavanto"),
        array('id' => 2, 'name' => "No sotavento"),
        array('id' => 3, 'name' => "No norte do arquipélago"),
    ),
    1 => array(
        array('id' => 1, 'name' => "Na ilha do fogo"),
        array('id' => 2, 'name' => "Na ilha de santiago"),
        array('id' => 3, 'name' => "Na ilha de brava"),
    ),
    2 => array(
        array('id' => 1, 'name' => "Verdairo"),
        array('id' => 2, 'name' => "Falso"),
    ),

);

$questoes      =  $data['rows']['questions'][1];

$alternativas  =  $data['rows']['aresponses'][1];

foreach ($questoes as $key => $value) {

    echo 'Questao: ' . $value['name'] . '<br />';

    echo 'Alternativas';

    foreach ($alternativas[$key] as $key2 => $value2 ) {

        echo 'Alternativa: ' . ($key2 + 1) . ' : ' . $value2['name'] . "<br />";

    }

    echo '<br /><br />';

}

To test code outside your project, test Here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.