循环遍历2个数组以找出应该检查哪些复选框
I have 2 arrays, $categories_filters and $adds_filters. They both return results. When printed using print_r, they return data in following format:
$categories_filters returns data like this:
Array
(
[0] => Array
(
[filterid] => 67
[catid] => 1
[filtername] => FILTERNAME1
[sorder] => 1
[visible] => 1
)
[1] => Array
(
[filterid] => 68
[catid] => 1
[filtername] => FILTERNAME155
[sorder] => 2
[visible] => 1
)
.....
$adds_filters returns the following:
Array
(
[0] => Array
(
[addfilterid] => 9
[addid] => 5
[filterid] => 67
)
[1] => Array
(
[addfilterid] => 10
[addid] => 5
[filterid] => 163
)
)....
I am trying the following: I have checkbox for each value in the $categories_filters. If the filterid exists in the $adds_filters array, i want that checkbox to be checked, otherwise, i want that checkbox just to be displayed unchecked.
I am trying to achieve that with the following code:
if($categories_filters) {
foreach ($categories_filters as $key1=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
foreach ($adds_filters as $key2=>$af) {
if($af['filterid'] == $value['filterid']) {
echo "<input type='checkbox' name='categoriesfilters[]' id= '".$value['filterid']."' value='" .$value['filterid'] ."' checked = 'checked' class='zcheckbox' />";
} else {
echo "<input type='checkbox' name='categoriesfilters[]' id= '".$value['filterid']."' value='" .$value['filterid'] ."' class='zcheckbox' />";
}
}
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>"
}
}else {
echo "No filters";
}
Quick catchers will realize that I get 2 checkboxes displayed for each value in the arrays, instead of one (checked or unchecked)
I guess that different approach is needed here.
One suggestion would be that instead of looping through the entire $adds_filters
array everytime, store all the 'filterid'
into a variable and just check if the $value['filterid']
exists inside that array.
The code below uses functions in_array and array_map.
Try this -
if($categories_filters) {
//Added this
$addfilterids = array_map(function($v){return $v['filterid'];}, $adds_filters);
foreach ($categories_filters as $key1=>$value){
echo "<div class='chb_group'>";
echo "<span class='custom_chb_wrapper'>";
//Modified from here-
if(in_array($value['filterid'], $addfilterids)){
echo "<input type='checkbox' name='categoriesfilters[]' id= '".$value['filterid']."' value='" .$value['filterid'] ."' checked = 'checked' class='zcheckbox' />";
}else{
echo "<input type='checkbox' name='categoriesfilters[]' id= '".$value['filterid']."' value='" .$value['filterid'] ."' class='zcheckbox' />";
}
//^Modified uptil here.
echo "<label>" .$value['filtername']. "</label>";
echo "</span>";
echo "</div>"
}
}