$a=array(array("product"=>"apple","quantity"=>2),
array("product"=>"Orange","quantity"=>4),
array("product"=>"Banana","quantity"=>5),
array("product"=>"Mango","quantity"=>7),
);
$b=array("product"=>"Lemon","quantity"=>9);
array_push($a,$b);
//$a[]=$b;
$max=sizeof($a);
for($i=0; $i<$max; $i++) {
while (list ($key, $val) = each ($a[$i])) {
echo "$key -> $val ";
} // inner array while loop
echo "<br>";
} // outer array for loop
Adding elements to multidimensional array from database table.
We will try to add elements to a multidimensional array by taking records from a database table. Here we are looping through all the records to display records and at the same time adding the record to array.
Note that each student record is an array and it is added to our main array. There are two columns we used and you can extend it to include more columns.
Here is the full code
<?Php
require "config.php";// database connection
$sql="SELECT * FROM student";
$my_array=array();
foreach ($dbo->query($sql) as $row) {
//echo "$row[id] , $row[name],$row[class],$row[mark]<br>";
$data=array("id"=>$row['id'],"name"=>$row['name']);
$my_array[]=$data;
}
echo $my_array[5]['name']; // displaying single record
echo "<hr>";
$max=sizeof($my_array);
for($i=0; $i<$max; $i++) {
// displaying all the elements
while (list ($key, $val) = each ($my_array[$i])) {
echo "$key -> $val <br>";
} // inner array while loop
} // outer array for loop
?>
Displaying single element ( record )
echo $my_array[5]['name']; // displaying single record