Browse an Array Saved a Query in PHP

2

Greetings to all, my subject is the following, I have saved a query

$datosMotivos= array();

while($row = mysqli_fetch_array($result)) { 

$cod=$row['cod'];
$descripcion=$row['descripcion'];
$motivo=$row['motivo'];
$lugar=$row['lugar'];

$datosMotivos[] = array('cod'=> $cod, 'descripcion'=> $descripcion, 'motivo'=> $motivo, 'lugar'=> $lugar); 
}

I want to go through it in the same PHP file for another process I'm doing, what is the proper way to go through that saved array? I am open to your suggestions and advice, thank you for your time.

P.D: Clarifying the topic, for my particular case I need to go through the array outside of the while I show them, since assign values that are inside this while I already know how to do it.

    
asked by Gutierrez 21.11.2016 в 05:37
source

2 answers

4

To traverse the Array $datosMotivos after having stored there each row returned by the query (out of the while) ... It could be iterated through a foreach (array_expression as $ value) .

while($row = mysqli_fetch_array($result)){
    ....
 }
foreach ($datosMotivos as  $value) {
    print_r($value);/* Obtener el Array completo por cada fila devuelta de la consulta*/
    echo $value['cod'];/* Obtener un campo especifico del array */
 }
    
answered by 21.11.2016 / 05:55
source
2

I think you mean to access the array rows outside of the while, if so, your problem lies in the scope of the variables

to solve it we will have to copy it in another variable that will be called a copy

$datosMotivos= array();
$copia;
while($row = mysqli_fetch_array($result)) { 
$copia=$row;
$cod=$row['cod'];
$descripcion=$row['descripcion'];
$motivo=$row['motivo'];
$lugar=$row['lugar'];

$datosMotivos[] = array('cod'=> $cod, 'descripcion'=> $descripcion, 'motivo'=> $motivo, 'lugar'=> $lugar); 
}

//aca puedes trabajar con la variable copia, asi como lo hiciste con $row dentro del ciclo while
$cod=$copia['cod'];
$descripcion=$copia['descripcion'];
$motivo=$copia['motivo'];
$lugar=$copia['lugar'];
  

to access the elements dynamically:

foreach ($copia as  $element) {}
    
answered by 21.11.2016 в 05:57