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?
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