how to make checked checkbox in two arrays - php

Here i have two arrays 1.response 2.selected_amenties,in first array value i displayed in checkbox, now i want to make checked values for Swimming Pool and Power Backup because of this values equal to the first array (response ), how can do this ?
<?php
$response = Array
(
Array
(
"id" => "57e2340eaebce1023152759b",
"name" => "Squash Court",
"amenityType" => "Sports"
),
Array
(
"id" => "57e23470aebce1023152759d",
"name" => "Swimming Pool",
"amenityType" => "Sports"
),
Array
(
"id" => "57e2347caebce1023152759e",
"name" => "Power Backup",
"amenityType" => "Convenience"
),
Array
(
"id" => "57e23486aebce1023152759f",
"name" => "Day Care Center",
"amenityType" => "Convenience"
)
);
$selected_amenties = Array( "0" => "Swimming Pool",
"1" => "Power Backup"
);
foreach($response as $amenity)
{
?>
<div class="checkbox">
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>
</div>
<?php
}
?>

Try like this:
<?php
foreach($response as $amenity)
{
$checked = in_array($amenity['name'], $selected_amenties) ? 'checked' : '';
?>
<div class="checkbox">
<input type="checkbox" class="aminit" name="aminit" value="<?php echo $amenity['name'] ?>" <?php echo $checked; ?>><?php echo $amenity['name']?>
</div>
<?php
}
?>

$selected_amenties = array('Swimming Pool', 'Power Backup');
foreach($response as $amenity) {
$check = '';
in_array($amenity, $selected_amenties) and $check = ' checked="checked" ';
echo '<div class="checkbox">';
echo '<input type="checkbox" ' . $check . ' class="aminit" name="aminit" value="<?php echo $amenity['name']?>"><?php echo $amenity['name']?>';
echo '</div>';
}

Related

Distinct in foreach loop. To many result because of two loops

I've a custom system that provides adding new information in custom columns.
I've two tables in my database. One for my value data and the second for the columns (data fieds).
Above you see a image from my form that is build by custom data fields with data per field.
Only in my for each i get for every data a extra loop so that is why i got from every data field two. How can I fix this?
<?php foreach ($list as $key => $value) { ?>
<?php foreach ($dataList as $data) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<?php if($key == $data['name']) { ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" value="<?php echo trim($data['value']); ?>" required>
<?php }else{ ?>
<input type="text" class="form-control" name="value_<?php echo trim($data['name']); ?>" placeholder="<?php echo ucfirst($key); ?>">
<?php } ?>
</div>
</div>
</div>
<?php } ?>
<?php } ?>
$list you'll find a list of data fields and in $dataList you'll find records of data.
Database structure:
data:
['id','hash','field_id','value']
Example of data:
['id' => 1, 'hash' => 123, 'field_id' => 1, 'value' => 'food']
Fields:
['id','name']
Example of fields:
['id' => 1, 'name' => 'firstname']
Below you'll find the foreach variables:
$data = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['data.value,data.uid,fields.name,data.id,fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"', true);
$dataItem = processing('read', 'data JOIN fields ON data.field_id = fields.id', ['fields.category_id'], 'uid = "' . trim($_GET['datalist']) . '"');
$fieldList = processing('read', 'fields', ['name'], 'category_id = "'. trim($dataItem['category_id']) . '"',true);
$list = [];
foreach($fieldList as $key => $value) {
$list[$value['name']] = $value['name'];
}
Update:
I've update my own question because the other answers didn't resolved my problem. The only problem on my answer is, that when I update it doesnt look at the id of the item but at the name, so i can't save two items with the same name.
<?php foreach ($dataItems as $key => $value) { ?>
<div class="row clearfix">
<div class="col-xl-12">
<div class="form-group form-group-default">
<label><?php echo ucfirst($key); ?></label>
<input type="text" placeholder="<?php echo ucfirst($key); ?>" class="form-control" name="<?php echo trim($key); ?>" value="<?php echo trim($value); ?>">
</div>
</div>
</div>
<?php } ?>
method:
public function getDataListItems(int $category, array $list) {
global $dbh;
$query = 'SELECT data.value, data.uid, fields.name FROM data JOIN fields ON data.field_id = fields.id WHERE fields.category_id = "' . trim($category) . '" ORDER BY uid';
$sql = $dbh->prepare($query);
$sql->execute();
$values = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach ($values as $row) {
if (!isset($items[$row['uid']])) {
$items[$row['uid']] = array_fill_keys($list, ''); // if it needs to dynamically generated
$items[$row['uid']]['uid'] = $row['uid'];
}
$items[$row['uid']][$row['name']] = $row['value'];
}
return $items;
}
Return:
array (
'7d1f4f8e906245f' =>
array (
'Voornaam' => 'Bettina',
'Achternaam' => 'Les',
'Initialen' => 'pop',
'uid' => '7d1f4f8e906245f',
),
'7d1f4f8e906245g' =>
array (
'Voornaam' => 'Simone',
'Achternaam' => '',
'Initialen' => '',
'uid' => '7d1f4f8e906245g',
),
'7d1f4f8e906245l' =>
array (
'Voornaam' => 'test',
'Achternaam' => 'Kül',
'Initialen' => 'lol',
'uid' => '7d1f4f8e906245l',
),
'7d1f4f8e906245s' =>
array (
'Voornaam' => 'Joshua',
'Achternaam' => 'Mas',
'Initialen' => '',
'uid' => '7d1f4f8e906245s',
),
'gGcYEJdRYJ1vqcn' =>
array (
'Voornaam' => '',
'Achternaam' => 'Hello',
'Initialen' => '',
'uid' => 'gGcYEJdRYJ1vqcn',
),
)

Issues while displaying Arrays php

I am very new to php and I am trying to learn php by myself. I have an array
<?php
$age=array("A"=>"test",
"Arating"=>"37",
"B"=>"test2",
"Brating"=>"40",
"c"=>"test3",
"crating"=>"41",
"D"=>"test4",
"Drating"=>"42");
?>
I would like to create a form from array like
Expected output:
<html>
<form action="" name="test" method="post"/>
<input name="A" value="test" id="test"/>
<textarea rows="4" cols="50" name="Arating" >
37
</textarea>
<br>
<input name="B" value="test2" id="test2"/>
<textarea rows="4" cols="50" name="Brating" >
40
</textarea>
<br>
<input name="C" value="test3" id="test3"/>
<textarea rows="4" cols="50" name="Crating" >
41
</textarea>
<br>
<input name="D" value="test4" id="test4"/>
<textarea rows="4" cols="50" name="Drating" >
42
</textarea>
</form>
</html>
<html>
here A B C D will be input type values and textarea should always be Arating,Brating,Crating,Drating
I tried:
<form action="" name="test" method="post"/>
<?php
foreach($age as $key => $value){?>
<input name="<?php echo $key ?>" value="<?php echo $value ?>" id="test"/>
<textarea rows="4" cols="50" name="Arating" >
<?php echo $value ?>
</textarea>
<?php } ?>
Input name always:A,B,C,D
Textarea:Arating,Brating,Crating,Drating
output is totally wrong.I am totally new to php
try this: As per your array
<?php
$age=array("A"=>"test",
"Arating"=>"37",
"B"=>"test2",
"Brating"=>"40",
"c"=>"test3",
"crating"=>"37",
"D"=>"test4",
"Drating"=>"40");
?>
<form action="" name="test" method="post">
<?php
$i=0;
foreach($age as $key => $value)
{
if($i%2==0)
{?>
<input name="<?php echo $key ?>" value="<?php echo $value ?>" id="test"/>
<?php
}
else
{?>
<textarea rows="4" cols="50" name="<?php echo $key ?>" ><?php echo $value ?> </textarea>
<?php }
$i++;
} ?>
</form>
As it is your array is not optimised to do this. Technically you could do some checks using the modulos operator % and get the 1st and 2nd options combined with if statements and the like but this gets messy and if you ever have items out of order or want to change or add a new option in future then you will be in a whole word of pain.
It is better to re-arrange your array into a multi-dimensional array and then loop over it and access each item by it's key name. It will make your code much more understandable and maintainable in the long run too.
The code below should work better for you:
<?php
$ages = array(
"A" => [
"val" => "test",
"name" => "Arating",
"num" => "37"
],
"B" => [
"val" => "test2",
"name" => "Brating",
"num" => "40"
],
"C" => [
"val" => "test3",
"name" => "crating",
"num" => "37"
],
"D" => [
"val" => "test4",
"name" => "Drating",
"num" => "40"
]
);
foreach($ages as $key => $age){ ?>
<input name="<?php echo $key ?>" value="<?php echo $age['val'] ?>" id="<?php echo $age['val'] ?>" />
<textarea rows="4" cols="50" name="<?php echo $age['name'] ?>"><?php echo $age['num'] ?></textarea>
<?php } ?>
Try like that.
<form action="" name="test" method="post"/>
<?php
foreach($age as $key => $value) {
if(!is_numeric($value) ) {
?>
<input name="<?php echo $key ?>" value="<?php echo $value ?>"
id="test"/>
<?php } else { ?>
<textarea rows="4" cols="50" name="<?php echo $key ?>" >
<?php echo $value ?>
</textarea>
<?php } } ?>
<?php
$age = [
"A" => "test",
"Arating" => "37",
"B" => "test2",
"Brating" => "40",
"c" => "test3",
"crating" => "41",
"D" => "test4",
"Drating" => "42"
];
?>
<form action="" name="test" method="post"/>
<?php
foreach ($age as $key => $value) {
if (strlen($key) == 1) { ?>
<input name="<?php echo $key ?>" value="<?php echo $value ?>" id="<?=$value;?>"/>
<?php } else { ?>
<textarea rows="4" cols="50" name="<?php echo $key ?>"><?php echo $value ?></textarea>
<?php } ?>
<?php } ?>
Another option if you have AA for a key
<?php
$count = 1;
foreach ($age as $key => $value) {
if ($count == 1) { ?>
<input name="<?php echo $key ?>" value="<?php echo $value ?>" id="<?= $value; ?>"/>
<?php } elseif($count==2) { ?>
<textarea rows="4" cols="50" name="<?php echo $key ?>"><?php echo $value ?></textarea>
<?php } ?>
<?php
if ($count == 2) {
$count = 0;
}
$count++;
?>
<?php } ?>
A more scalable solution,
<?php
$age = [
[
'name' => 'A',
'value' => 'test',
'type' => 'textInput'
],
[
'name' => 'Arating',
'value' => '37',
'type' => 'textarea'
],
[
'name' => 'B',
'value' => 'test2',
'type' => 'textInput'
],
[
'name' => 'Brating',
'value' => '40',
'type' => 'textarea'
],
[
'name' => 'c',
'value' => 'test3',
'type' => 'textInput'
],
[
'name' => 'crating',
'value' => '41',
'type' => 'textInput'
],
[
'name' => 'D',
'value' => 'test4',
'type' => 'textInput'
],
[
'name' => 'Drating',
'value' => '42',
'type' => 'textInput'
],
];
?>
<form action="" name="test" method="post"/>
<?php
foreach ($age as $key => $value) {
if ($value['type'] == 'textInput') { ?>
<input name="<?php echo $value['name'] ?>" value="<?php echo $value['value'] ?>" id="<?= $value['value']; ?>"/>
<?php } elseif ($value['type'] == 'textarea') { ?>
<textarea rows="4" cols="50" name="<?php echo $value['name'] ?>"><?php echo $value['value'] ?></textarea>
<?php } ?>
<?php } ?>

Put an array within an array, display a drop down in php

I am trying to create a form using php. I am unsure how to put the country drop down menu right after the city field. I am not sure the best way to do this I have my array.
$labels = array (
"first_name" => "First Name",
"last_name" => "Last Name",
"address" => "Address",
"city" => "City",
"email" => "E-mail",
"phone" => "Phone", );
$country = array (
"select" => "",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico", );
$submit = "Submit";
?>
Here is the display code:
<?php
echo "<h2>Customer Info</h2>";
echo "<form action='checkBlank.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if($field == "city") {
echo "<label for='country'>Country</label>
<select id='country' name='country'>";
foreach ( $country as $select => $option)
{
echo "<option value='$value'>$option</option>";
}
echo "</select>";
}
}
echo "<div id='submit'>
<input type='submit' value='$submit'></div>
</form>";
?>
Test the field name, and if it's the city, do another loop to display the country drop-down.
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if ($field == 'city') {
echo '<div><select name="country">';
foreach ($country as $short => $long) {
echo "<option value='$short'>$long</option>";
}
echo '</select></div>';
}
}
BTW, it's conventional to use an empty value for the Select One option. Standard form validation tools will recognize this as meaning no option was selected, if you mark the field as required.
'Looks like #Barmar beat me to the punch on this one but i have a similar solution
$labels = array (
"first_name" => "First Name",
"last_name" => "Last Name",
"address" => "Address",
"city" => "City",
"email" => "E-mail",
"phone" => "Phone", );
$country = array (
"select" => "Select One",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico", );
$submit = "Submit";
echo "<h2>Customer Info</h2>";
echo "<form action='checkBlank.php' method='post'>";
foreach ( $labels as $field => $label)
{
echo "<div class='field'>
<label for='$field'>$label</label>
<input id='$field' name='$field' type='text'
size='42' /></div>";
if($field == "city") {
echo "<label for='country'>Country</label><select id='country' name='country'>";
foreach ( $country as $value => $option)
{
echo "<option value='$value'>$option</option>";
}
echo "</select>";
}
}
echo "<div id='submit'>
<input type='submit' value='$submit'></div>
</form>";
I would personally do it like this:
$fields = array (
array(
"name" => "first_name",
"label" => "First Name",
),
array(
"name" => "last_name",
"label" => "Last Name",
),
array(
"name" => "address",
"label" => "Address",
),
array(
"name" => "city",
"label" => "City",
),
array(
"name" => "country",
"label" => "Country",
"options" => array (
"" => "Select One",
"us" => "United States",
"ca" => "Canada",
"mx" => "Mexico",
),
),
array(
"name" => "email",
"label" => "E-mail",
),
array(
"name" => "phone",
"label" => "Phone",
),
);
foreach($fields as $field) {
echo "<div class='field'><label for='{$field['name']}'>{$field['label']}</label>";
if (isset($field['options'])) {
echo "<select name='{$field['name']}'>";
foreach ($option as $value => $title) {
echo "<option value='$value'>$title</option>";
}
echo '</select>'
} else {
echo "<input id='{$field['name']}' name='{$field['name']}' type='text' size='42' />";
}
echo "</div>";
}

Associative Multidimensional Array

I want to be able to use a variable (which is a value that is imputed in a textbox) in an
Associative Multidimensional Array and print out the rest of the array values associated with it.
here is what i have so far that doesnt work
<html>
<body>
<form method="post" action="newcal.php">
<table>
<tr>
<td> Item #: </td>
<td> <input type=text name= txtitem > <br> </td>
<td>
</td>
<td> <fieldset style = "width:60px">
<input type=submit value = "Get Data" name= getdata>
<input type=submit value = "Add to Cart" name= addto>
<input type=submit value = "Get Total" name= gettotal>
</fieldset>
</td>
</tr>
</table>
</form>
<?php
$item = isset($_POST['txtitem']);
$stuff = array(
array("id" => 1,"name" => "Apples","price" => 50 ),
array("id" => 2,"name" => "Pineapples","price" => 125 ),
array("id" => 3,"name" => "Mango","price" => 35 ),
array("id" => 4,"name" => "Banana","price" => 25 ),
array("id" => 5,"name" => "Naseberry","price" => 38 ));
if(isset($_POST['getdata']))
{
foreach ($stuff as $row)
{
if ($row['id'] == $item)
{
$name = $row['name'];
$price = $row['price'];
}
}
echo $name;
echo $price;
}
?>
</body>
</html>
I think your error is with the following line:
$item = isset($_POST['txtitem']);
$item is being set to a boolean value. You probably want something like this:
$item = (isset($_POST['txtitem']) ? intval($_POST['txtitem']) : null);

php foreach loop from multidimensional array

I have a multidimensional array which I want to display in a foreach loop. I've been looking at lots of tutorials but I haven't been able to make it work yet.
This is my array and foreach loop:
$events = array(
array( Name => "First Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
),
array( Name => "Second Event",
Date => "12/13/14",
Time => "12:13",
Description => "event description"
),
array( Name => "Third Event",
Date => "12/13/14",
Time => "12:13"
Description => "event description"
)
);
foreach($events as $event) {
echo "<div class=\"event\"><strong>";
echo $event[Name];
echo "</strong><em>";
echo $event[Date] . " at " . $event[Time];
echo "</em><div>";
echo $event[Description];
echo "</div></div>";
}
and here is how I want it to display:
<div class="event">
<strong>Event Name</strong><em>Date at Time</em>
<div>
Description
</div>
</div>
I would appreciate any help you could give. Thanks!
The keys are missing quotes and Time => "12:13" missing comma "," at the end:
<?php
$events = array(
array( "Name" => "First Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Second Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
),
array( "Name" => "Third Event",
"Date" => "12/13/14",
"Time" => "12:13",
"Description" => "event description"
)
);
foreach($events as $event) {
?>
<div class="event">
<strong><?php echo $event["Name"];?></strong><em><?php echo $event["Date"];?></em>
<div><?php echo $event["Description"];?></div>
</div>
<?php
}
?>
Output
First Event 12/13/14
event description
Second Event 12/13/14
event description
Third Event 12/13/14
event description
The keys should be in quotes. E.g.: 'Name' rather than Name
<?php foreach($events as $event): ?>
<div class="event">
<strong><?php echo $event['Name'] ?></strong><em><?php echo $event['Date'] ?> at <?php echo $event['Time'] ?></em>
<div>
<?php echo $event['Description'] ?>
</div>
</div>
<?php endforeach; ?>
Try this:
foreach($events as $record) {
$name = $record["name"];
$date = $record["date"];
$time = $record["time"];
$description = $record["description"];
print("
// your html code with the variables here
");
}

Categories