0

Hi, How can I loop this out?

<input type="text" name="attr[1][value][1][name]">
<input type="text" name="attr[1][value][1][price]">
<input type="text" name="attr[2][value][1][name]">
<input type="text" name="attr[2][value][1][price]">

Any Solution?

3
Contributors
2
Replies
24
Views
3 Years
Discussion Span
Last Post by diafol
0

You can loop 3 times:

foreach($_POST['attr'] as $k1 => $v1)
{
    foreach($v1 as $k2 => $v2)
    {
        foreach($v2 as $k3 => $v3)
        {
            echo $v3['name'];
            echo $v3['price'];
        }
    }
}

An alternative is to use an iterator:

$arr = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($_POST['attr']));

foreach($iterator as $key => $value)
{
    $arr[$key][] = $value;
}

for($i = 0; $i < count($arr); $i++)
{
    echo $arr['name'][$i];
    echo $arr['price'][$i];
}
0

There's no point, the code would be longer than the html.

If however it was dynamic and there were many many attr:

$startIndex = 1; $lastIndex = 20; //hard-coded for example
$output = '';
for($x=$startIndex;$x<=$lastIndex;$x++)
{
    $output .= "<input type='text' name='attr[$x][value][1][name]'>\n<input type='text' name='attr[$x][value][1][price]'>";
}
echo $output;

Or many variations on the same theme.

Edited by diafol

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.