In the "while" method adds to the array

Asked

Viewed 53 times

0

I’m trying to produce a script that when I query in mysql it returns an array, so far ok, but the goal is to make this query turn into an edited json. Example:

{"changelog":{"count":2,"news":{"ola":"testando1","ola2":"testando2"}}}

And in C# I make a code that returns this and puts it in a Textbox. But I don’t know how to add an item in an array when returning the data in array.

$array1 = array();
while( $row = mysql_fetch_array($query)){
   // adiciona no array a $row[1] e $row[2] por exemplo: no lugar do 'ola' fica o $row[1] e no lugar do 'testando1' fica o $row[2]
}

but the query we will assume is 30 items the query is limited to LIMIT 0,10

TABLE:

CAMPO        | VALOR
ID           | TIPO INT, NOT NULL, AUTO INCREMENT
TITLE        | TIPO TEXT, NOT NULL // $row[1]
DESCRIPTION  | TIPO LONGTEXT, NOT NULL // $row[2]

ID  |  TITLE  |  DESCRIPTION
0   |  ola    | testando1
1   |  ola2   | testando2

  • 1

    From what I understand, you want to create an array of arrays and encode in JSON, that’s it?

  • yes! after the news he will put {"TITLE":"DESCRIPTION"} until the mysql array is finished

  • One more question, {"changelog":{"count":2,"news": these data are fixed?

  • yes! changelog is the opening and Count is the mysql_num_rows

2 answers

2


Guy sees if that’s more or less what you want:

<?php
$aux = array();
while($dado = mysqli_fetch_array($sql)){
    $title = $dado['title'];
    $valor = $dado['valor'];

    $aux2 = array("titulo" => $title, "valor" => $valor);

    array_push($aux, $aux2);

}
$array = array("cahangelog" => array("count" => 2, "news" => $aux));

echo json_encode($array);

EXIT:

{"cahangelog":{"count":2,"news":[{"titulo":"testando","valor":"valor teste"}]}} 

-1

See if this solves :

$array1 = array();
while( $row = mysql_fetch_array($query)){
   $array1[]  = array("valor 1", "valor 2");
}

Browser other questions tagged

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