How to encode json with multiple objects in PHP

Asked

Viewed 336 times

1

I need the following result:

{
    "sala": [{
        "horario": "18:30",
        "data": "Seg e Terça"
    }, {
        "horario": "10:30",
        "data": "Quarta Terça"
    }]
}

UPDATE

I’m doing it like this in PHP:

                 /*criando objeto vazio*/
                $object = new stdClass();
                /*passando array para o objeto vazio*/
                $object->salas = array();

                $quantidade= $_POST['quantidade'];//imagina que aqui tem 2
           for($i=0;$i<count($quantidade);$i++){ //aqui vai rodar 2x

                $horario = $_POST['horarios_'.$quantidade]; //ATUALIZAÇÃO
                $dias= $_POST['dias_'.$quantidade]; //ATUALIZAÇÃO

                /*percorrendo o objeto vazio*/  
                foreach ($object as $key => $value) {           
                    $object_data = new stdClass();
                    $object_data->horario = $horario;//valor da hora
                    $object_data->data = $dias;//valor do dia
                    array_push($object->salas, $object_data);
                }

                /*codificando json*/    
                echo json_encode($object);

           }

But I’m getting it wrong:

{
    "salas": [{
        "horario": ["18:30", "10:30"],
        "data": ["Seg e Terça, Quarta Terça"]
    }]
}

Once I can generate the correct structure, how can I print the information according to each schedule and date

  • It’s nothing sorry I think I’ve got it, sorry

  • Okay. Give to help?

  • I tested it on ideone and it worked check it out https://ideone.com/j1qgjT

  • Right, but when there’s more than one value to insert into $object_data->horario and $object_data->data, give this last json of the question, I think it is on account of the foreach that involves it, how to solve?

  • How you got the data originally?

  • clears the $object_data variable at the end of foreach. unset($object_data)

  • @Euler01 I think that is not the problem, because at the beginning of the foreach already has $object_data = new stdClass(); then it starts clean right?. @Lollipop put like this the array of "out".

  • Guys, I updated and put the for to better understand and POST to value the variables.

  • @Neuberoliveira already had a problem similar to this, which I solved by cleaning the variable. Since then I test everything. kkkkk

  • @Euler01, nothing yet :(

Show 5 more comments

1 answer

1

The problem was that the variables $horario and $dias were passing an array, so when there was more than one loop in the for he created a [] in the json then I determined the index [0] and it worked.

Browser other questions tagged

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