Multidimensional array

This is know as array of array or multidimensional array. We have used user a two dimensional array . Here is the example of creating an array
$a=array(
																								array("path"=>"php_tutorial","section"=>"php"),
																								array("path"=>"sql_tutorial","section"=>"sql"),																			      																								array("path"=>"javascript_tutorial","section"=>"js"),
																							array("path"=>"html_tutorial","section"=>"html"),
); 


Now to display the elements of this array we can use like this.
$max=sizeof($a);
for($i=0; $i<$max; $i++) { 

while (list ($key, $val) = each ($a[$i])) { 
echo "$key -> $val <br>"; 
} // inner array while loop

} // outer array for loop
The output is here
path -> php_tutorial 
section -> php 
path -> sql_tutorial 
section -> sql 
path -> javascript_tutorial 
section -> js 
path -> html_tutorial 
section -> html
To display individual element
echo $a[2]['path'];
Output is here
javascript_tutorial

Adding elements to multidimensional array.

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.
$data=array("id"=>$row['id'],"name"=>$row['name']);
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
You can read more on how to connect to database



Be the first to post comment on this article :


Google+

Post Comment This is for short comments only. Use the forum for more discussions.






OPINION POLL

What is the most important factor of a web site
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us
©2000-2015 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer