douxing9641
douxing9641
2014-05-08 12:20

PHP比较数据库中的2个数组,复选框=检查是否找到任何值

已采纳

I have a column(apps) in the database which has a list of words separated with commas like - AAA, BBB, CCC I have another column(appsSelected) that will be populated in the same format with the words that the user checks with check boxes values.

On one page i list all of the words in apps with check boxes beside them, on submit it inserts those checked into appsSelected. On another page it lists only the words in the appsSelected column, I have managed to grab appsSelected and explode it to list each word.

<?php
$appsString = $pi_row['appsSelected'];
// break $appsString using the comma as the delimiter
$appliances = explode(', ', $appsString);                                    
// loop through and print all the words
echo '<ul>';
    for ($i = 0; $i < count($appliances); $i++)
    {   
        echo '<li>' . $appliances[$i] . '</li><br/>';
    }
echo '</ul>';
?>

The problem i have is when i go back to the page with check boxes, i want them to stay checked on the words that are in appsSelected. So im guessing i have to compare apps with appSelected and echo out either a checked box or un-checked depending on what words match.

for ($i = 0; $i < count($appliances); $i++)
{
$codes = array($pi_row['apps']);
$codesSelected = array($pi_row['appsSelected']);
//if (in_array($appliances[$i], $codesSelected)) {

if (array_intersect($ap, $aps)) {
    echo '<li><input type="checkbox" checked="checked" value="' . $appliances[$i] . '"     name="applianceCheckbox[]">' . $appliances[$i] . '</input></li><br/>';
} else{
    echo '<li><input type="checkbox" value="' . $appliances[$i] . '" name="applianceCheckbox[]">' .      $appliances[$i] . '</input></li><br/>';
}
}

The code above only works if appsSelected matches the entire array in apps: for example in the apps column - AAA, BBB, CCC if i tick AAA and BBB or any other combonation that doesnt involve matching every word in apps no check boxes get ticked but if i tick AAA, BBB, CCC the check boxes will return all ticked

I need to find a way to see if any word in apps matches any word in appSelected.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsmlf1207915 dsmlf1207915 7年前

    Use in_array like you did in your comment, you have to pass it the correct array though:

    $codesSelected = explode(', ', $pi_row['appsSelected']);
    
    for ($i = 0; $i < count($appliances); $i++)
    {
        if (in_array($appliances[$i], $codesSelected)) {
            echo '<li><input type="checkbox" checked="checked" value="' . $appliances[$i] . '"     name="applianceCheckbox[]">' . $appliances[$i] . '</input></li><br/>';
        } else {
            echo '<li><input type="checkbox" value="' . $appliances[$i] . '" name="applianceCheckbox[]">' .      $appliances[$i] . '</input></li><br/>';
        }
    }
    
    点赞 评论 复制链接分享