I'm still figuring out the object oriented stuff and am looking for some advice on how to utilize ArrayObject properly on multidimensional arrays.
The thing I need to do here is take a multidimensional array and build a function that will output the data into a table using functionality within the ArrayObject class. If it were a simple array I don't think I'd have any problem with it, but I'm trying to use getIterator and I'm just coming up short on how to pull out the actual data in this case.
Here's my code so far...
Code:
<?php
class userData extends ArrayObject {
public function displayAsTable() {
$user = array(
array("user_id" => "1", "first_name" => "Bob", "last_name" => "Sanders"),
array("user_id" => "2", "first_name" => "Dave", "last_name" => "Greggors"),
array("user_id" => "3", "first_name" => "Susan", "last_name" => "Bowie"),
array("user_id" => "4", "first_name" => "Gary", "last_name" => "Anderson")
);
$userArrayObject = new ArrayObject($user);
//Iterate over the values in the ArrayObject
echo "<table border=\"1\">";
for($iterator = $userArrayObject->getIterator();
$iterator->valid();
$iterator->next())
{
echo "<tr><td>".$iterator->key()."</td><td>".$iterator->current()."</td></tr>";
}
echo "</table>";
}
}
userData::displayAsTable();
?>
I'm guessing I need to do another for loop within the existing loop but I just can't seem to find much good info on the arrayobject stuff with examples where I can get that "aha!" moment.
Now I know I can achieve what I want to accomplish here doing this...
Code:
<?php
class userData extends ArrayObject {
public function displayAsTable() {
echo "<table border=\"1\"><tbody>";
$user = array();
$user[] = array("user_id" => "1", "first_name" => "Bob", "last_name" => "Sanders");
$user[] = array("user_id" => "2", "first_name" => "Dave", "last_name" => "Greggors");
$user[] = array("user_id" => "3", "first_name" => "Susan", "last_name" => "Bowie");
$user[] = array("user_id" => "4", "first_name" => "Gary", "last_name" => "Anderson");
foreach ($user as $key => $val) {
$userArrayObject = new ArrayObject($val);
foreach ($userArrayObject as $key => $val) {
if($key == "user_id") {
echo "<tr>";
}
echo "<td>".$val."</td>";
if($key == "last_name") {
echo "</tr>";
}
}
}
echo "</table></tbody>";
}
}
userData::displayAsTable();
?>
But remember I want to use the functionality within the ArrayObject class and to give the most flexibility with the function. Basically I wan to be able to instantiate the class and set a new user with a set function and to get the data using a get function.
I understand the basics of building a class, a function, what scope is, how to chain methods, and how to instantiate a class and modify it, etc. What I don't know yet are the ins and outs of the built in classes and functionality and how to properly use them.
** EDIT NOTE **
Once I figure out how to properly iterate over the multidimensional array and set the data in objects then I'm sure I can then build out the set and get functions.