I am attempting to take an array of values and build a php form from those values.
The array is at the bottom to keep the question clear. The array structure is:
- Item
- Item
- Item with Child
-Item
-Item
- Item with Child
-Item
-Item
Here is what I want to output each item but if the item has a child, just output the name of the parent and create fields for the children.
I created this:
function renderTest2(array $data)
{
$html = '<ul>';
foreach ($data as $item) {
$html .= '<li>';
foreach ($item as $key => $value) {
if (is_array($value)) {
$html .= renderTest2($value);
} else {
if (array_key_exists('children', $item)) {
$html .= $item['name'];
} else {
$html .= $item['name'] . "<input type=\"text\" value=\"\"> <br/>";
}
}
}
$html .= '</li>';
}
$html .= '</ul>';
return $html;
}
Which gave me this output:
But I don't understand why it is duplicating items. What am I doing wrong?
Here is the test array I used:
$aFullArray = array();
$aFullArray[] = array("name" => "Adam", "address" => "123 main", "phone" => "000-000-0000");
$aFullArray[] = array("name" => "Beth", "address" => "123 main", "phone" => "000-000-0000");
$aChildren = array();
$aChildren [] = array("name" => "Mike", "address" => "123 main", "phone" => "000-000-0000");
$aChildren[] = array("name" => "Nancy", "address" => "123 main", "phone" => "000-000-0000");
$subChild = array();
$subChild [] = array("name" => "Peter", "address" => "123 main", "phone" => "000-000-0000");
$subChild [] = array("name" => "Paul", "address" => "123 main", "phone" => "000-000-0000");
$aChildren [] = array("name" => "Oscar", "address" => "123 main", "phone" => "000-000-0000",
"children" => $subChild);
$aFullArray[] = array("name" => "Charlie", "address" => "123 main", "phone" => "000-000-0000",
"children" => $aChildren);
$aFullArray[] = array("name" => "Danny", "address" => "123 main", "phone" => "000-000-0000");


foreach()is duplicate twice, that the structure of yourforeachreads each type in the array, so since you've got a "name", "address" and "phone" theforeach()grabs all three of them, and then gets told show the "name"foreach()value you've come accross wich equals 3 times.