[英]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 结果: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
. 您只需更新创建两个键=>值对id
和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[] =
. 正如您在这里可能注意到的那样,我删除了j
索引(您不需要它;我想您将其用作多维数组的“第一级索引”),并添加了以下语句: $lista[] =
。 "Magic" happens just there: with this command ( $arrayname[] =
) you can append to existent array a new element. “魔术”就在那里发生:使用此命令( $arrayname[] =
),您可以将一个新元素附加到现有数组中。
However I don't know from where you're obtaining $id
and $nome
so this snippet could fail due to undefined variables and similar 但是我不知道您从哪里获得$id
和$nome
因此由于未定义变量和类似原因,此代码片段可能会失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.