Add array within array

Asked

Viewed 1,039 times

0

How to add an array within another array ? I’ve got these two, I want to add the bottom one on the top, with the name "answers"

Array
(
    [0] => Array
        (
            [id] => 0
            [unidade] => 4
            [exercicio] => 1
            [enunciado] => Complete with the correct pronoun
            [pergunta] => Marcus and his brother talk about politics between ???
            [imagem] => 
            [tipo] => complete1
            [respostacorreta] => themselves
        )

    [] => Array
        (
            [0] => They
            [1] => Them
            [2] => Themselves
        )

)

My final json result should look something like:

    {
    "0": {
        "id": "0",
        "unidade": "4",
        "exercicio": "1",
        "enunciado": "Complete with the correct pronoun",
        "pergunta": "Marcus and his brother talk about politics between ???",
        "imagem": null,
        "tipo": "complete1",
        "respostas": [
                      "They",
                      "Them",
                      "Themselves"
                  ],
        "respostacorreta": "themselves"
    }
}

My current code is like this:

$sql = new Sql();
$exercicioarray = $sql->select("SELECT * FROM tb_exercicios");
$arrayrespostas = explode(',',$exercicioarray[0]['respostas']);
unset($exercicioarray[0]['respostas']);
$exercicioarraysemresposta = $exercicioarray;
$exercicioarraycomresposta = $exercicioarraysemresposta[$exercicioarraysemresposta[0]['respostas']] = $arrayrespostas;



//print_r($exercicioarraysemresposta);
//print_r($arrayrespostas);

$response = json_encode($exercicioarraysemresposta, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);

2 answers

2


Perhaps it would be better if you return everything in the same SQL query, but as I have no details of your database do not to do so.

You have some mistakes in your code. Generally to add new elements in an array the following syntax is used:

//vazio
$array1 = [];
$array2 = [];

//para adicionar elementos com indice numerico
$array1[] = 1;
$array1[] = 2;
$array1[] = 3;

//no final $array1 = [1, 2, 3]

//para adicionar elementos com chave
$array2['campo1'] = 1;
$array2['campo2'] = 2;
$array2['campo3'] = 3;

//$array2 = ['campo1' => 1, 'campo2' => 2, 'campo3' => 3]

Applying to your code is:

//se estiver na mesma linha da proxima instrução, 
//só o array respostas será copiado
$exercicioarraysemresposta[0]['respostas'] = $arrayrespostas;
$exercicioarraycomresposta = $exercicioarraysemresposta;

A more complete test:

<?php
 $exercicioarraysemresposta = [
     [
         'id' => 0,
         'unidade' => 4,
         'exercicio' => 1,
         'enunciado' => 'Complete with the correct pronoun',
         'pergunta' => 'Marcus and his brother talk about politics between ???',
         'imagem' => null,
         'tipo' => 'complete1',
         'respostacorreta' => 'themselves'
     ]
 ];

$arrayrespostas = [
    'They',
    'Them',
    'Themselves'
];

//se estiver na mesma linha da proxima instrução, só o array respostas será copiado
$exercicioarraysemresposta[0]['respostas'] = $arrayrespostas;
$exercicioarraycomresposta = $exercicioarraysemresposta;

var_dump($exercicioarraycomresposta);

echo json_encode($exercicioarraycomresposta);

?>

Generates as output json:

[
  {
    "id": 0,
    "unidade": 4,
    "exercicio": 1,
    "enunciado": "Complete with the correct pronoun",
    "pergunta": "Marcus and his brother talk about politics between ???",
    "imagem": null,
    "tipo": "complete1",
    "respostacorreta": "themselves",
    "respostas": [
      "They",
      "Them",
      "Themselves"
    ]
  }
]
  • It worked, thanks. I think I understood the logic, the problem now is to treat this index of the array, because the database will return me several arrays of these. but I already have an idea with loop

  • what would it be like to return everything in the same SQL query? my database is structured the way q the final json gets a porem that the answers is a string separated by commas

  • 1

    @Igoroliveira Based on this new information, you only need the $exercicioarray. Basically stop doing the unset and in place make $exercicioarray[0]['respostas'] = $arrayrespostas;. Which looks better to iterate in a loop, something like for($i=0; $i < count($arrayrespostas); $i++) $exercicioarray[$i]['respostas'] = explode(',',$exercicioarray[$i]['respostas']);

  • Very good, exactly what I needed, Thanks Juven_v

0

change

$exercicioarraycomresposta = $exercicioarraysemresposta[$exercicioarraysemresposta[0]['respostas']] = $arrayrespostas;

for

 $exercicioarraycomresposta = $exercicioarraysemresposta;
 $exercicioarraycomresposta[0]['resposta'] = $arrayrespostas;
  • it created another array, not inside array 0

  • I edited and now no longer creates a new

Browser other questions tagged

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