Add data obtained mysqli to a multi array

3

I'm trying to add the data obtained from a select and order them to an array in PHP.

I want to accommodate the array in this way:

$array = array(noticias => array("1" => array ("titulo" => "Noticia 1", "autor" => "Pepe", "fecha" => "03/08/2018", "contenido" => "<b>Hola Mundo</b><br>")));

This is my code, so far I only get the last record in this way.

$sql = "SELECT * FROM noticias LIMIT 2";
$data=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($data)){
$datos_acomodados = array("titulo" => $row['titulo'], "autor" => $row['autor'], "fecha" => $row['fecha'], "contenido" => $row['contenido']);
    //echo $row['titulo'];
    //echo $row['autor'];
    //echo $row['fecha'];
    //echo $row['contenido'];
}
mysqli_close($conn);

I have this doubt and also in the way I am doing it.

    
asked by robotini 06.08.2018 в 23:38
source

1 answer

2

You need to declare the variable $datos_acomodados as an array. The correct way would be like this:

$sql = "SELECT * FROM noticias LIMIT 2";
$data=mysqli_query($conn,$sql);
$datos_acomodados = array();
while($row=mysqli_fetch_array($data)){
$datos_acomodados[] = array("titulo" => $row['titulo'], "autor" => $row['autor'], "fecha" => $row['fecha'], "contenido" => $row['contenido']);
    //echo $row['titulo'];
    //echo $row['autor'];
    //echo $row['fecha'];
    //echo $row['contenido'];
}
mysqli_close($conn);
    
answered by 06.08.2018 / 23:40
source