Forum Moderators: coopster

Message Too Old, No Replies

Problem w/ preserving checked state in a recursive function

         

nick33

11:08 pm on Feb 24, 2008 (gmt 0)

10+ Year Member



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. :(

<?php 
function make_list($array, &$lineage = array()) {
?>
<ul>
<?php
// make a list item for each keyword in the array
foreach($array as $key => $value) {
?>
<li>
<?php
// if the current element is an array, recursively call the function
if(is_array($value)) {
// print the current item
echo $key;

// recursively list the subarray
$lineage[] = $key;
make_list($value, $lineage);
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
}
?>

nick33

5:39 am on Feb 25, 2008 (gmt 0)

10+ Year Member



Just to clarify, what I'm trying to do now is come up with a way to look for $value in $_POST['keyword'][level_1][level_2]...[level_n] where n is the times the function has recursively been called. Is this approach even practical? When I first call make_list(), I pass it my keyword array, which is actually just an array of arrays categorized into related groups. I'd like to preserve that grouping when the form is submitted.

Once again, I'd greatly appreciate any advice.

coopster

9:48 pm on Feb 25, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, nick33.

I'm not quite following what you want to do here. If you have the array built, just check to see if the POST value is in the pre-built array by using isset [php.net]. But it seems like you are doing that, so I am confused as to where you are hung up here?