PHP将逗号分隔的字符串与数组的键进行比较

时间:2014-04-02 15:54:44

标签: php arrays

我试图将逗号分隔的字符串与下面的数组键进行比较,因此如果它们匹配,我可以将这些复选框标记为已选中。

我坚持这个。如何才能做到这一点?我可以比较两个数组,但我不能想出一种比较逗号分隔字符串和数组键的方法。你能帮忙吗?

$countries = array (
    "US" => "United States Of America",
    "GB" => "United Kingdom",
    "CA" => "Canada",
    "SE" => "Sweden",
    "AU" => "Australia",
);

$str = 'US,CA,SE'; // This comes from a MySql table

foreach ($countries as $code=>$name) {

    if(//value in comma seperated string == array key i.e US == US) {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'" checked>'.$name.'</div>'.PHP_EOL;
    } else {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'">'.$name.'</div>'.PHP_EOL;
    }
}

2 个答案:

答案 0 :(得分:4)

$countries = array (
    "US" => "United States Of America",
    "GB" => "United Kingdom",
    "CA" => "Canada",
    "SE" => "Sweden",
    "AU" => "Australia",
);

$str = 'US,CA,SE';
$selected_countries = explode(',', $str);

foreach ($countries as $code=>$name) {

    if(in_array($code, $selected_countries)) {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'" checked>'.$name.'</div>'.PHP_EOL;
    } else {
        echo '<div><input type="checkbox" name="country[]" value="'.$code.'">'.$name.'</div>'.PHP_EOL;
    }
}

在这里,我使用explode()将三个国家/地区放在一个数组中。然后,我会找到与$countries使用array_keys()的密钥匹配的密钥,以获取这些密钥,array_intersect()找到匹配项。然后,我使用$countriesin_array()中的键与我们在字符串中的每个键进行比较。

答案 1 :(得分:1)

$selected_countries = array_flip(explode(',', $str));

foreach ($countries as $code => $name) {
    echo '<div><input type="checkbox" name="country[]" value="'.$code.'" ' . 
        (isset($selected_countries[$code]) ? 'checked' : '') .
        '>'.$name.'</div>'.PHP_EOL;
}