I'm trying to return the name and value by looping through an array and for that I'm using the array_walk_recursive
function. All works fine, except that it's returning the nested array indexes instead of the name. In the example below I want the indexes to be 'name3' but as the main array is dynamic, the loop can't be specific for that nested array.
Array
Array
(
[name1] => value
[name2] => value
[name3] => Array
(
[0] => value1
[1] => value2
)
)
Function
function test($value, $name) {
echo "<input type='hidden' name='$name' value='$value'>";
}
array_walk_recursive($array, 'test');
Output
<input type='hidden' name='name1' value='value'>
<input type='hidden' name='name2' value='value'>
<input type='hidden' name='0' value='value1'>
<input type='hidden' name='1' value='value2'>
It was simpler than i thought, a nested foreach is needed for that.
foreach ($array as $name => $value) {
if (is_array($value)) {
foreach ($value as $name2 => $value2) {
echo '<input type="hidden" name="'.$name."[]".'"
value="'.$value2.'">';
}
} else {
echo '<input type="hidden" name="'.$name.'" value="'.$value.'">';
}
}
try to do something like this
foreach ($array as $name => $value) {
if(is_array($value))
{
// convert it to string by the way you want
}
echo "<input type='hidden' name='$name' value='$value'>";
}