Mirko
Mirko

Reputation: 41

Multidimensional Array to html MultiDimensional checkbox

I've an array like this:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => a
                            [1] => d
                            [2] => Array(...)
                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => a
                            [1] => e
                            [2] => Array(...)
                        )

                )

        )

)

I would like to create, from this array, an set of checkbox nested in HTML <li> statement. I've created a function for make the nested <li>

function nested_li(array $array){
    $output = '<ul>';
    foreach($array as $key => $value){
        $output .= "<li><strong>$key: </strong>\n";
        if(is_array($value)){
            $output .= nested_li($value)."\n";
        }else{
            $output .= $value."\n";
        }
        $output .= '</li>'."\n";
    }
    $output .= '</ul>'."\n";
    return $output;
}

Now the trouble is to create in this a nested checkbox list, for example:

<input type="checkbox" name="check[0][0][0][0]" value="a"/>
<input type="checkbox" name="check[0][0][0][1]" value="d"/>
<input type="checkbox" name="check[1][0][0][0]" value="a"/>
<input type="checkbox" name="check[1][0][0][1]" value="e"/>

I need to do this for a category system, for choose what category to display.

Upvotes: 0

Views: 320

Answers (1)

ɹɐqʞɐ zoɹǝɟ
ɹɐqʞɐ zoɹǝɟ

Reputation: 4370

Hope this helps you :)

use recursiveiteratoriterator

$arr=array
(
    0 => array
        (
            0 => array
                (
                    0 => array
                        (
                            0 => 'a',
                            1 => 'd',
                            2 => 's' //or Array(...)
                        ),

                ),

        ),

    1 => array
        (
            0 => array
                (
                    0 => array
                        (
                            0 => 'a',
                            1 => 'e',
                            2 => 'l'
                        ),

                ),

        ),

);

$flat = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($flat as $item) {
  $a[]= $item;
}
foreach($a as $i)
{
    echo '<input type="checkbox" name="'.$i.'" value="a"/>'.$i;
}

Upvotes: 2

Related Questions