Print only matched values from two Associative arrays - php

I have these two associative arrays.
I want to print the matched category_id with CHECKED and the rest Un-CHECKED
Here is what I tried.
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $current_item_categories)){
echo 'CHECKED';
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}

You should do sometjhing like this:
Step1: Modify your $current_item_categories array like this:
$currentCategories = array();
foreach($current_item_categories as $currCat) {
array_push($currentCategories, $currCat['category_id']);
}
Step2: Now I am using the same logic as applied by you, with a very little modification.
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $currentCategories)){
$checked = 'checked="checked"';
}else {
$checked = "";
}
echo '<input ' . $checked . 'type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}
Note: code not tested.

Well, you could first make an associative array of current item categories, you just key it by the category id for fast lookup.
<?php
$currentCatIds = array();
foreach ($current_item_categories as $category) {
$currentCatIds[$category['category_id']] = 1;
}
foreach ($all_available_categories as $category) {
$catid = $category['category_id'];
// Forgot this one
$checked = isset($currentCatIds[$catId]) ? 'checked' : '';
echo '<input ' . $checked . ' type="checkbox" name="item_categories_checkbox[]" value="' . $catid . '" />' . $category['category_name'] . '<br />';
}

foreach ($all_available_categories as $category) {
foreach ($next_available_categories as $category1) {
if($category['category_id'] == $category1['category_id']){
echo 'CHECKED'; break;
}
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' .$category['category_id'] . '">' . $category['category_name'] . "</br>";
}

The idea is really quite easy: loop all categories and then for each category check whether this category is checked. You are trying to do the latter using the PHP function in_array(), but that function doesn't search multi-dimensional. So that would only work if you would have an array of category id's: $ids = array('9', '13');, and then check the category id using in_array().
So if we make these modifications it works:
$ids = array();
foreach($current_item_categories as $category) {
$ids[] = $category['category_id'];
}
foreach ($all_available_categories as $category) {
if(in_array($category['category_id'], $ids)){
echo 'CHECKED';
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '">' . $category['category_name'] . '</br>';
}
An other way to do this would of course be to use two nested loops. This would no longer require an array of id's and allows for other checks to be made:
foreach ($all_available_categories as $category) {
foreach ($current_item_categories as $c) {
if ($category['category_id'] == $c['category_id']) {
echo 'CHECKED';
}
}
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '">' . $category['category_name'] . '</br>';
}
Finally, you should realize that your code doesn't check the checkboxes, it only prints the word "CHECKED". If that isn't what you want, you should add a checked attribute to your input element.

Credit to Frog's answer.
Here is the fully working code.
$current_ids = array();
foreach ($current_item_categories as $category) {
$current_ids[] = $category['category_id'];
}
foreach ($all_available_categories as $category) {
echo '<input type="checkbox" name="item_categories_checkbox[]" value="' . $category['category_id'] . '"';
if (in_array($category['category_id'], $current_ids)) {
echo ' CHECKED ';
}
echo ' >' . $category['category_name'] . '</br>';
}

Related

Need to perform an if statement inside a php foreach loop

I'm working with the Filemaker API - which is similar to sql - basically its pulling data from a fields and from a list.
I'm trying to set up an if statement inside my foreach loop so that it adds a the tag selected="selected" to my select option in my html
Here's the code
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
}
$list_menu .= '</select>';
echo $list_menu;
?>
How can I add an if statement like this to the foreach loop?
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
The body of the foreach loop is simply a block of statements so you can put in as many as you want, such as with:
foreach ($values as $value) {
$list_menu .='<option value="' . $value . '">' . $value . '</option>';
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
}
However, are you sure you have the right attribute for the option tag? If it's your intent to select a specific option, checked is not the right method (it's meant for checkbox input fields). The selected attribute is the correct one for the HTML option tag.
So you would be better off with something like:
# The default is orange.
$default_value = "orange";
# Process every option.
foreach ($values as $value) {
# Add [<option value="X"].
$list_menu .= '<option value="' . $value . '"';
# Add [ selected] ONLY for default one.
if ($value == $default_value) {
$list_menu .= ' selected';
}
# Add [>X</option>].
$list_menu .= '>' . $value . '</option>';
}
This will give you the option tags as desired but the one where the value matches the default value will also have the selected attribute attached.
Assuming $values held the array {"red", "black", "orange", "yellow"}, you would end up with (formatted nicely here for the purposes of the answer):
<option value="red"> red </option>
<option value="black"> black </option>
<option value="orange" selected> orange </option>
<option value="yellow"> yellow </option>
I assuming that you already know how to get your $businessJudgement , so that code should be something like this
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
if ($businessJudgements == 'No') {
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
} else {
$list_menu .='<option value="' . $value . '" selected >' . $value . '</option>' ;
}
}
$list_menu .= '</select>';
echo $list_menu;
?>

Print specific array value via function argument

$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]

Modify function which dynamically populates select elements to use arrays from db

I'm trying to modify a function that I've been using to dynamically populate <select> element to use arrays from a database. The original function used hard-coded arrays to populate the elements, and pre-selected the option which matched the db value.
The revised function creates the element, but it's only adding the first value from the db. How can I modify it so that it will loop through all the values that should be added to the <select> element?
PHP Function and Query
<?php
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM student");
$stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
?>
Populate Select Element
<select name="fname">
<?php
echo printSelectOptions(array($row['fname']));
?>
</select>
The Original Function & Code for Populating an Element
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
<select name="fname">
<?php
$options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
$selected = $row['fname'];
echo printSelectOptions($options, $selected);
?>
</select>
Since you have only fetched a single row via fetch(), only a single value is getting passed into your function printSelectOptions(). Instead, get all rows via fetchAll()
and modify your function to receive the full array, plus a string which is the column name (array key) you want to print from.
// All rows into $rows...
$rows = $stmt->fetchAll();
// Make the function accept the full 2D array, and
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
Then call the function as:
echo printSelectOptions($rows, $currentSelection, 'fname');
The way it is right now, the option's value attribute is populated by the array key, which would be numbered from zero. That's similar to your original array version, but it might be more useful to specify another column name like id as the key column.
// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
And would be called as:
echo printSelectOptions($rows, $currentSelection, 'id', 'fname');

Alternative ways to set select element's value during validation of a form?

Normally I would do something like this:
<select name="myselect">
<option value="opt1" <?=($_POST['myselect']=="opt1"?"SELECTED":"")?>>Option 1</option>
<option value="opt2" <?=($_POST['myselect']=="opt2"?"SELECTED":"")?>>Option 2</option>
</select>
However this time I've taken a list of all the countries in a select from this website: http://snippets.dzone.com/posts/show/376
To go through each of those and put in the validation will be insane.
There is a php solution in the comments but it seems somewhat inelegant.
Is there an alternative way to do this or something similar? I would prefer not to use javascript, and I'm not sure I want to rely on the browser caching.
Thanks
// I'm using integers as key values in this example. Modify as needed.
$countries = array(
1 => 'Some Country',
// etc...
);
// Sanitize as needed, casting to integer in my example
$selectedCountryCode = isset( $_POST['myselect'] ) ? (int) $_POST['myselect'] : null;
$select = '<select name="myselect">';
foreach( $countries as $countryCode => $countryName )
{
$selected = $selectedCountryCode == $countryCode ? ' selected="selected"' : '';
$select .= '<option value="' . $countryCode .'"' . $selected . '>' . $countryName . '</option>';
}
$select .= '</select>';
echo $select;
You could create select with an array like this:
$options = array('opt1' => 'Option1', 'op2' => 'Option2');
foreach ($options as $o => $v)
{
if ($_POST['myselect'] == $o)
echo '<option value="' . $o . '" selected="selected">' . $v . '</option>';
else
echo '<option value="' . $o . '">' . $v . '</option>';
}
Add countries to value-label array
Generate options with loop
foreach ($countries as $value => $label) {
$isSelected = $_POST['myselect'] == $value ? ' selected="selected"': '';
echo '<option value="' . $value . '"' . $isSelected . '>' . $label . '</option>';
}

PHP count problem?

For some reason my $count displays the number 1 first instead of 0 I really don't know what's going on I want count to start at 0 and display 0 first then 1, 2 and so on can someone help me correct this problem?
PHP code.
function make_list ($parent = 0, $count = 0, $depth = 0) {
global $link;
if($count == 0){
echo '<ol class="cat-width">';
} else {
echo '<ol class="cat-depth">';
}
foreach ($parent as $id => $cat) {
if($cat['parent_id'] == '0'){
echo '<li><input type="checkbox" name="cat[]" id="cat-' . $cat['id'] . '" value="' . $cat['id'] . '" />
<label for="cat-' . $cat['id'] . '" class="label-headers">' . $cat['category'] . '</label>';
} else {
$indent = str_repeat(' ', $depth * 3);
echo '<li>' . $indent . '<input type="checkbox" name="cat[]" id="cat-' . $cat['id'] . '" value="' . $cat['id'] . '" />
<label for="cat-' . $cat['id'] . '">' . $cat['category'] . '</label>';
}
if (isset($link[$id])) {
make_list($link[$id], $count+1, $depth+1);
}
echo '</li>';
}
echo '</ol>';
}
$dbc = mysqli_query($mysqli,"SELECT * FROM categories ORDER BY parent_id, category ASC");
if (!$dbc) {
print mysqli_error();
}
$link = array();
while (list($id, $parent_id, $category, $depth) = mysqli_fetch_array($dbc)) {
$link[$parent_id][$id] = array('parent_id' => $parent_id, 'id' => $id, 'category' => $category, 'depth' => $depth);
}
make_list($link[0], $depth+1);
The first call to make_list should be:
make_list($link[0],0, $depth+1);
rather than
make_list($link[0], $depth+1);
You are trying to give default value to $count only without giving default value to $depth. That is not possible.
Your call make_list($link[0], $depth+1); is actually assigning $depth+1 to $count and using the default value of 0 for $depth
try using null or 0 as second parameter and do check out func_get_args() http://php.net/manual/en/function.func-get-args.php. you wont need to set function parameters in this case. just call this function to get all the arguments you passed and manipulate it manually.
You're adding 1 to depth when calling the function. This means that inside the make_list function depth with only be 0 if called with a value of -1.
Your $count is nowhere displayed. Do you mean then 1. 2. ... from the <ol> ? As far as I can see it always starts with 1.

Categories