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
// 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]
<?php
// make a list item for each keyword in the array
foreach($array as $key => $value) {
?>