mardi 19 juillet 2016

generating checkboxes for a specific key in multidimensional array

I have 2 multidimensional arrays $ex and $al which when printed (print_r) produces the following output:

Array $investmentProgramExistingCriteriaoutput:

Array
(
[0] => Array
    (
        [key1] => 1
        [key2] => 4
        [criteriaID] => 25
    )

[1] => Array
    (
        [key1] => 2
        [key2] => 4
        [criteriaID] => 26
    )

)

Array $criteria output:

Array
(
[0] => Array
    (
        [criteriaID] => 27
        [key3] => 1
        [key4] => Some value
        [key5] => Yes
        [key6] => 3
        [key7] => 1
    )

[1] => Array
    (
        [criteriaID] => 25
        [key3] => 5
        [key4] => Some other value
        [key5] => 1, 2, 3
        [key6] => 1
        [key7] => 1
    )

[2] => Array
    (
        [criteriaID] => 26
        [key3] => 1
        [key4] => Some different value
        [key5] => Ναί
        [key6] => 1
        [key7] => 1
    )

)

I am trying to generate check boxes for each item in $criteria array. However, if the criteriaID in the $criteria array exists in the $investmentProgramExistingCriteriaoutput array, the checkbox should be checked, if not, it should be unchecked.

I am trying to do that with the following code:

foreach ($criteria as $val) {
    foreach ($investmentProgramExistingCriteria as $existingcriteria) {
        if($val['criteriaID'] == $existingcriteria['criteriaID']) {
            echo "<input type='checkbox' name='criteria[]' value=".$val['criteriaID']." style='margin-bottom:20px;float:left;' checked='checked' />&nbsp;&nbsp;&nbsp;";
            echo "<span style='line-height:20px;'>".$val['criteriaDescription'] ."</span><br /><br />";  
        } else {
            echo "<input type='checkbox' name='criteria[]' value=".$val['criteriaID']." style='margin-bottom:20px;float:left;' />&nbsp;&nbsp;&nbsp;";
            echo "<span style='line-height:20px;'>".$val['criteriaDescription'] ."</span><br /><br />";   
            }
        }
    }

As you can see from the above array values, I should get 3 checkboxes, from which 2 should be checked. However this code print 6 checkboxes instead of 3,

2 of the 6 printed checkboxes them are checked (correctly). How can I get rid of duplicate checkboxes?




Aucun commentaire:

Enregistrer un commentaire