Reputation: 11
I am trying to display a multidimensioal array and I am doing that in a very static way. I wonder how I could achieve the same results with a foreach.
I've tried accessing individualy which works but the coding technique seems not acceptable.
Table
array(
"name" => "Bob",
"occupation" => "employee",
"salary" => 1500,
"specialty" => "programmer"
),
array(
"name" => "Sally",
"occupation" => "manager",
"salary" => 2300,
"specialty" => "human resources management"
),
array(
"name" => "Jane",
"occupation" => "employee",
"salary" => 800,
"specialty" => "secretary"
),
);
My function
function printTable($table){
echo "<h2>Employee #1</h2>";
echo $table[0]["name"];
echo $table[0]["occupation"];
echo $table[0]["salary"];
echo $table[0]["specialty"];
echo "<h2>Employee #2</h2>";
echo $table[1]["name"];
echo $table[1]["occupation"];
echo $table[1]["salary"];
echo $table[1]["specialty"];
echo "<h2>Employee #3</h2>";
echo $table[2]["name"];
echo $table[2]["occupation"];
echo $table[2]["salary"];
echo $table[2]["specialty"];
}
Desired result http://prntscr.com/n5jnnu
Upvotes: 0
Views: 83
Reputation: 1336
Check this.You have 2D array so we need 2 for loops, and then we print the key values (name is key) and the values.Also i have added a counter to print the number of employees.
$counter = 1;
echo "<ul>";
foreach($table as $val){
echo "<h2>Employee #$counter</h2>";
foreach($val as $key => $val1){
echo "<li>$key: $val1 </li>";
}
echo "<br>";
$counter++;
}
echo "</ul>"
Upvotes: 1
Reputation: 47874
You can easily use the keys and values available in your multidimensional array.
To calculate the employee number, add 1 to the index (first level keys).
By writing the <h2>
element outside of the <ul>
tag, you achieve the tabbed-in look of your posted screenshot.
Use css to style the font of your <h1>
and <h2>
tags.
Tested Code:
$array = [
["name" => "Bob", "occupation" => "employee", "salary" => 1500, "specialty" => "programmer"],
["name" => "Sally", "occupation" => "manager", "salary" => 2300, "specialty" => "human resources management"],
["name" => "Jane", "occupation" => "employee", "salary" => 800, "specialty" => "secretary"]
];
echo "<h1>Employees and managers</h1>";
foreach ($array as $index => $row) {
echo "<h2>Employee #" , $index + 1 , "</h2>";
echo "<ul>";
foreach ($row as $label => $value) {
echo "<li>$label: $value</li>";
}
echo "</ul>";
}
Output:
Upvotes: 0