简体   繁体   中英

Add data in a multidimensional array dynamically

I am needing to add data dynamically into a multidimensional array. The data comes from a query in the database. I can see through the "echo" all elements, but in time to add to the multidimensional vector data and overwrite only the last record is added.

My example below:

$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();

$numu = $stmtu->rowCount();
    $j = 0;
    $lista;

    if ($numu > 0) { 

        $colunas = 3;

        while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
            extract($rowu);                         
            $lista['id'] = $id;
            $lista['nome'] = $nome;
            $j++;
        }
    }

The result: id - 6 nome - teste

This is the last record added.

Thanks!!!

You don't create a multi dimensional array by now. You just update create two key => value pairs id and nome . If you want to store multiple of them you have to create a multidimensional array which means an array inside another array:

$lista = array(); // init your array!

while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
    extract($rowu);                         
    $lista[] = array(
        'id' => $id,
        'nome' => $nome
    );
    $j++;
}

Or do it even smarter (if the keys in the final array are the same as the column names):

$lista = array(); // init your array!

while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
    $lista[] = $rowu;
    $j++;
}

Modify your code as follows

$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();

$numu = $stmtu->rowCount();
$lista = array();

if ($numu > 0) { 
  $colunas = 3;

  while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
    extract($rowu);                         
    $lista[] = array('id' => $id, 'nome' => $nome);
  }
}

As you probably noticed here, I've removed j index (you don't need it; I suppose that you would use it as "first-level-index" of your multidimensional array) and added that statement: $lista[] = . "Magic" happens just there: with this command ( $arrayname[] = ) you can append to existent array a new element.

However I don't know from where you're obtaining $id and $nome so this snippet could fail due to undefined variables and similar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM