convert sql result into two-dimensional array in php

0

I want to put the results of an sql query in a two-dimensional array. The table would be something like id - > 1 name - > pepe last- > Garcia and other fields ... and I want you to put it in a two-dimensional array array [index] ['same name as the field in the table']. I have managed to do it as it comes down but there are too many fields to put them by hand and, besides, I'm sure there must be another way.

    <?php
include "conexion.php";

$consulta="SELECT * FROM 'tabla' WHERE nombre like 'Juan';";
$resultado=$conexion->query($consulta) or die("No puedo realizar la consulta");
$i=0;
while ($array=$resultado->fetch_array()){
$arrayauxliar[$i]['id']=$array['id'];
$arrayauxliar[$i]['nombre']=$array['nombre'];
/*aqui vendrían un churro de campos*/
$i++;
}
    
asked by Jaroso Jaroso 01.11.2017 в 13:46
source

1 answer

1

You can get the keys of the array returned by the query and that way you can automatically assign the chord index to your name that would be the attributes of your table

<?php
    include "conexion.php";

    $consulta="SELECT * FROM 'tabla' WHERE nombre like 'Juan';";
    $resultado=$conexion->query($consulta) or die("No puedo realizar la consulta");
    $i=0;
    while ($array=$resultado->fetch_array()){
        //Obtengo las claves del arreglo que en tu caso son los atributos de la tabla (id, nombre, etc)
        $claves = array_keys($array);
        //Recorro el arreglo de las claves para ir asignando los datos al arreglo con los nombres de los atributos
        foreach($claves as $clave){
            $arrayauxliar[$i][$clave]=$array[$clave];
        }           
        $i++;
    }
    
answered by 01.11.2017 / 13:53
source