I have a query that looks for associations between 2 tables (posts and cats), which I managed to put into an array (arrays are new to me):
$result_cats = db->query("SELECT posts_cat.cat_id
FROM posts_cat
JOIN posts ON posts_cat.post_id = posts.post_id
WHERE post_id = '$post_id'");
if (!$result_cats->num_rows == 0) {
$rows = array();
while ($row = $result_cats->fetch_assoc()) {
foreach ($row as $key => $value) {
$row[$key] = ($value);
}
$rows[] = $row;
}
}
Sample array output:
Array ( [0] => Array ( [cat_id] => 20 ) [1] => Array ( [cat_id] => 43 ) [2] => Array ( [cat_id] => 76 ) )
Now, I'd like to somehow use this in a function, to call when building checkboxes, so we can decide if they should be checked, or not.
So, for example, if 43 exists in the array, add "checked"
<input type="checkbox" id="cat_id" name="cat_id" value="43" checked>
else:
<input type="checkbox" id="cat_id" name="cat_id" value="43">
I've done something similar to this before with the following...
function checked($a,$b)
{
if ($a == $b) {
echo " checked";
}
}
Then using something like:
<input type="checkbox" id="cat_id" name="cat_id" value="43" <?php echo isset($cat_id) ? checked(43,$cat_id) : "";?>>
I've been playing around with this for a while, but just can't figure out how to get it done with an array. I'm not even 100% if the way I'm thinking about this is the most efficient process. Help?
fetch_all()and then usearray_columnto get a simpler array: stackoverflow.com/a/65893279/231316!$result_cats->num_rows == 0doesn't do what you think it does. See Operator precedence. It should be!($result_cats->num_rows == 0)foreach ($row as $key => $value) { $row[$key] = ($value); }doesn't do anything, it's just assigning the values you took out of the array back into it.$cat_ids = array_column($result_cats->fetch_all(MYSQLI_ASSOC), 'cat_id');then you can simply do<input type="checkbox" id="cat_id" name="cat_id" value="43" <?php echo in_array(43, $cat_ids) ? "checked" : "";?>>