php 中的多维数组?
我在 PHP 中遇到数组问题。那么,让我们看看:我在数据库中有一个表“用户”,其中包含以下字段:“姓名、年龄、评级”。用户数量接近 100。我需要从数据库中获取所有用户,将其发布到数组,并使用 JSON end show 对其进行编码。所以我想,我需要执行以下操作:
- 从数据库获取一行。
- 将所有数据添加到某些数组字段,例如关联数组。
- 将该数组推送到某个数组容器。
- 将数组容器编码为 JSON。
但是当我尝试编码时,我只得到数组容器中的最后一个元素。我写了类似的东西:
$arrContainer = array();
$arr = array();
$i = 0;
while($row = getDataFromDB)
{
arr[$i] = $i;
arr["name"] = row["name"];
arr["age"] = row["age"];
array_push($arrContainer, $arr);
$i++;
}
JSON.encode($arrContainer);
问题:如何用一些数据制作数组数组?
I have a problem with arrays in PHP. So, lets see: I have a table "Users" in database with such fields: "name, surname, age, rating". The number of users is nearly 100. I need to get all of them from database, post it to array, encode them with JSON end show. So I suppose, I need to do the follows:
- Get one row from DB.
- Add all data to some array fields like associative array.
- Push that array to some array container.
- Encode array container to JSON.
But when I try to encode, I get only last element in array container. I writted something like that:
$arrContainer = array();
$arr = array();
$i = 0;
while($row = getDataFromDB)
{
arr[$i] = $i;
arr["name"] = row["name"];
arr["age"] = row["age"];
array_push($arrContainer, $arr);
$i++;
}
JSON.encode($arrContainer);
QUESTION: How can I make array of arrays with some data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
现在你得到 multiDimension-array 和可以Json编码吗
另外,一些数据库扩展可以自动将所有数据返回到多维数组。
请参阅 PDOStatement::fetchAll 手册
Now you get multidimensional-array and can Json encode it
Besides, some database extensions can returns all data to multidimensional array automatically.
See PDOStatement::fetchAll manual
试试这个:
try this:
您可以像 @RiaD 的答案一样创建数组
然后输出json为..
You can create array as in @RiaD's answer
and then output json as ..
您发布的代码是正确的,但是在以下几行中,您忘记将
$
放在$arr
变量之前:还有行
arr[$i] = $i;
可能应该类似于$arr['rowNum'] = $i;
让键与值相同似乎是多余的。应该说,按照 @RiaD 建议使用
$arrContainer[]=$row;
是获取行数组的更快方法,array_push()
更快捷旨在向数组添加多个值或者要将其视为堆栈。The code you have posted is correct, however in the following lines you forgot to put
$
before the$arr
variable:Also the line
arr[$i] = $i;
should probably be something like$arr['rowNum'] = $i;
having the key be the same as the value seems redundant.And it should be said that using
$arrContainer[]=$row;
as @RiaD suggested is a quicker way to get an array of the row,array_push()
is more intended to add multiple values to an array or if you want to treat it as a stack.我得到的回应:
response I get: