Problem w/ preserving checked state in a recursive function

Hi, I’m a total PHP noob and was hoping for some help. I’m trying to make a recursive function that takes an array of strings and produces a list of checkboxes.

The problem is located right at the call to isset() & in_array(). I’d like to use the $lineage array to tell PHP specifically where to check in $_POST to see if a variable exists in order to preserve the checked state. I can’t seem to figure out how to access a subarray that’s at an unknown depth at run time.

The only option I can think of is to start off at $_POST[keywords], see if $lineage[‘first’] exists at that level, if so, move into that subarary, then check $lineage[‘second’] and so on until you reach where you think the element would be, but that seems like a really clumsy way to go about doing things. Is there a better way? Or is my problem with the whole approach that I’m taking? Many thanks for any help, this has been causing me a headache all day. :(

[code] <?php
function make_list($array, &$lineage = array()) {
?>


    <?php
    // make a list item for each keyword in the array
    foreach($array as $key => $value) {
    ?>

  • <?php
    // if the current element is an array, recursively call the function
    if(is_array($value)) {
    // print the current item
    echo $key;
    					// going one level deeper, so push it onto the stack
    					$lineage[] = $key;
    					
    					// recursively call the function on the child generation
    					make_list($value, $lineage);
        	
    					// finished with a generation, so pop it off of the stack
    					array_pop($lineage);
    				}
    				// otherwise, it's not an array, display the contents
    				else {
    	?> 	
                <input name="keywords<?php
                foreach($lineage as $ancestor) { 
                    echo "[$ancestor]"; 
                } 
                ?>[]" id="<?php echo $value; ?>" value="<?php echo $value; ?>" type="checkbox" <?php
                    // preserve the input	
                    if( isset($_POST['keywords']) && in_array($value, $_POST['keywords']) ) {
                        ?>checked="checked" <?php
                    }
                ?>/>     
                <label for="<?php echo $value; ?>"><?php echo $value; ?></label>
        <?php
    				}
    	?>
        	</li>
        <?php 
    			}
    	?>
        </ul>
        <?php
    		}
    	?>[/code]

Multidimensional arrays are tricky, and you seem to be lost in the maze. Best would be to pull this code to a development machine (if it isn’t already) and use echo statements and other debugging tips and tricks (see my signature) to check out what your arrays contain, and how deep they go. Key functions you should use are is_array() and count().

Sponsor our Newsletter | Privacy Policy | Terms of Service