Issues while displaying Arrays php - 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 } ?>

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',
),
)

display tr tags based on first array count and compare with second array in PHP

I have two arrays. I want to display the tr tag based on the count of $daterange and inside this, I need to check the date value with the second array date value.
First array :
$daterange = ['01/10/2017','02/10/2017','03/10/2017','04/10/2017','05/10/2017'];
Second array :
$job = [0 => ['id' =>1,'date' => '03/10/2017'],
1 => ['id' =>2,'date' => '12/10/2017'],
2 => ['id' =>3,'date' => '14/10/2017'],
3 => ['id' =>4,'date' => '13/10/2017'],
4 => ['id' =>5,'date' => '03/10/2017'],
5 => ['id' =>6,'date' => '04/10/2017'],
6 => ['id' =>7,'date' => '05/10/2017'],
7 => ['id' =>8,'date' => '01/10/2017']
];
Html code :
<table>
<?php foreach($daterange as $key=>$day)
{
?>
<tr>
<td>
<?php foreach($job as $jdata){
if(($day->format('Y-m-d') == ($jdata->date)) {
?>
<input type="radio" checked class="radio-check" name="date" value="">
<?php
} else {
?>
<input type="radio" class="radio-check" name="date" value="">
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
But tr tag is displayed 8 times based on second array count.
How do I display tr 5 times, which is the count of the first array, and compare the date inside with the second array?
You only need one loop for this task and you shouldn't repeat whole lines when you are only modifying a single attribute in the line (as a matter of DRYness).
array_column() will sufficiently prepare the $job data.
This is what I recommend: (Demo)
$daterange = ['01/10/2017','02/10/2017','03/10/2017','04/10/2017','05/10/2017'];
$job = [0 => ['id' =>1,'date' => '03/10/2017'],
1 => ['id' =>2,'date' => '12/10/2017'],
2 => ['id' =>3,'date' => '14/10/2017'],
3 => ['id' =>4,'date' => '13/10/2017'],
4 => ['id' =>5,'date' => '03/10/2017'],
5 => ['id' =>6,'date' => '04/10/2017'],
6 => ['id' =>7,'date' => '05/10/2017'],
7 => ['id' =>8,'date' => '01/10/2017']
];
$job_dates=array_column($job,'date'); // generate 1-dimensional array of dates
echo '<table>';
foreach($daterange as $date){
echo "<tr><td><input type=\"radio\" class=\"radio-check\" name=\"date\" value=\"$date\"",(in_array($date,$job_dates)?' checked':''),'></td></tr>';
}
echo "</table>";
/* or write it over several lines like this:
echo '<table>';
foreach($daterange as $date){
echo '<tr>';
echo '<td>';
echo "<input type=\"radio\" class=\"radio-check\" name=\"date\" value=\"$date\"";
if (in_array($date,$job_dates)){
echo ' checked';
}
echo '>';
echo '</td>';
echo '</tr>';
}
echo "</table>";
*/
Output:
<table>
<tr><td><input type="radio" class="radio-check" name="date" value="01/10/2017" checked></td></tr>
<tr><td><input type="radio" class="radio-check" name="date" value="02/10/2017"></td></tr>
<tr><td><input type="radio" class="radio-check" name="date" value="03/10/2017" checked></td></tr>
<tr><td><input type="radio" class="radio-check" name="date" value="04/10/2017" checked></td></tr>
<tr><td><input type="radio" class="radio-check" name="date" value="05/10/2017" checked></td></tr>
</table>
Here you have my solution, very similar to yours.
I tried it and it works ok.
<?php
$daterange = ['01/10/2017', '02/10/2017', '03/10/2017', '04/10/2017', '05/10/2017'];
$job = [0 => ['id' => 1, 'date' => '03/10/2017'],
1 => ['id' => 2, 'date' => '12/10/2017'],
2 => ['id' => 3, 'date' => '14/10/2017'],
3 => ['id' => 4, 'date' => '13/10/2017'],
4 => ['id' => 5, 'date' => '03/10/2017'],
5 => ['id' => 6, 'date' => '04/10/2017'],
6 => ['id' => 7, 'date' => '05/10/2017'],
7 => ['id' => 8, 'date' => '01/10/2017']
]
?>
<table>
<?php
foreach ($daterange as $day) {
?>
<tr>
<td>
<?php
$i = 0;
$numJobs = count($job);
$dateFound = 0;
while ($i < $numJobs && !$dateFound) {
if ($job[$i]['date'] == $day) {
$dateFound = 1;
}
$i++;
}
if ($dateFound) {
?>
<input type="radio" checked class="radio-check" name="date" value="">
<?php
} else {
?>
<input type="radio" class="radio-check" name="date" value="">
<?php
}
?>
</td>
</tr>
<?php
}
?>
</table>
Inside each element of $daterange I look for that date inside $job array with a while loop. If I found it, it stops searching and displays the checked input. Else, if it goes through all the array and doesn't find that date, it displays the non checked input.
(You can just copy and paste it in your code)
So I created a function searchForDate that would check if the date exist in the second array or not, try the below code and here is the demo:
<?php
$daterange = ['01/10/2017','02/10/2017','03/10/2017','04/10/2017','05/10/2017'];
<table>
<?php foreach($daterange as $key=>$day)
{
?>
<tr>
<td>
<?php foreach($daterange as $key=>$day){
if(searchForId($day)) {
?>
<input type="radio" checked class="radio-check" name="date" value="">
<?php } else {
?>
<input type="radio" class="radio-check" name="date" value="">
<?php } ?>
</td>
</tr>
<?php } ?>
</table>
<?php
function searchForId($day) {
$job = [
0 => ['id' =>1,'date' => '03/10/2017' ],
1 => ['id' =>2,'date' => '12/10/2017'],
2 => ['id' =>3,'date' => '14/10/2017'],
3 => ['id' =>4,'date' => '13/10/2017'],
4 => ['id' =>5,'date' => '03/10/2017'],
5 => ['id' =>6,'date' => '04/10/2017'],
6 => ['id' =>7,'date' => '05/10/2017'],
7 => ['id' =>8,'date' => '01/10/2017']
];
foreach ($job as $key => $val) {
if ($val['date'] === $day) {
return $key;
}
}
return null;
}
?>
$job = [0 => ['id' =>1,'date' => '03/10/2017'/* ' here*/ ],
1 => ['id' =>2,'date' => '12/10/2017'],
2 => ['id' =>3,'date' => '14/10/2017'],
3 => ['id' =>4,'date' => '13/10/2017'],
4 => ['id' =>5,'date' => '03/10/2017'],
5 => ['id' =>6,'date' => '04/10/2017'],
6 => ['id' =>7,'date' => '05/10/2017'],
7 => ['id' =>8,'date' => '01/10/2017']
]
Try this as your for loop.
<table>
<?php
foreach ($job as $key => $jdata) {
if (in_array($jdata['date'], $daterange)) {
?>
<tr>
<td>
<input type="radio" checked class="radio-check" name="date" value="">
</td>
</tr>
<?php
}
}
?>
</table>

how to make checked checkbox in two arrays

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>';
}

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);

how to get the value of textbox in the same in php

i am working on textbox in which value is display after selecting value from the combo box .i need to get that value that appear in textbox for further computation in the same page.
here is the coding
<?php
$options = array(
'0' => array(
'title' => ' ',
'value1' => '',
'value2' => '',
),
'1' => array(
'title' => 'Islamabad',
'value1' => '31.41',
'value2' => '73.11',
),
'2' => array(
'title' => 'Lahore',
'value1' => '31.56',
'value2' => '74.35',
),
'3' => array(
'title' => 'Kharachi',
'value1' => '24.86',
'value2' => '67.01',
),
'4' => array(
'title' => 'Faisalâbâd',
'value1' => '31.41',
'value2' => '73.11',
),
'5' => array(
'title' => 'Gujrânwâla',
'value1' => '32.16',
'value2' => '74.18',
),
);
if (isset($_GET['option']) && isset($options[$_GET['option']])) {
echo json_encode($options[$_GET['option']]);
exit;
}
?>
<form>
<?php echo "SELECT " ?>
<select name="combo" id="combo">
<?php
foreach($options as $key_value => $option)
{
printf('<option value="%s">%s</option>', $key_value, $option['title']);
}
?>
</select>
<input type="text" name="hidden" id="textboxB" value="" />
<input type="text" name="hidden" id="textboxC" value="" />
<script type="text/javascript" src="jquery.min1.js"></script>
<script type="text/javascript">
$(function(){
$('#combo').change(function(){
$.getJSON("?", {
option : $(this).val()
}, function (data) {
$('#textboxB').val(data.value1);
$('#textboxD').val(data.value1);
$('#textboxE').val(data.value1);
$('#textboxC').val(data.value2);
});
});
});
</script>
i need to get the value of textboxB and textboxC in separate variable so that i can use theses value for further computation on the same page.
i want to use theses value in if -else statement like
if(textboxD==3.15)
{
$a=$b......
}
my requirement is to get these value in separate variable.
people plz help me in ths
You need to set your input names to arrays, such as:
<input type="text" name="hidden[]" id="textboxA" value="123" />
<input type="text" name="hidden[]" id="textboxB" value="654" />
<input type="text" name="hidden[]" id="textboxC" value="abc" />
<input type="text" name="hidden[]" id="textboxD" value="zyg" />
Remember, ID's are only useful for client-side. ID's never get posted, only the NAME and VALUE.
Now, in PHP, you can access these values via:
<?php
$hidden = !empty($_POST['hidden']) ? $_POST['hidden'] : false;
if($hidden) {
foreach($hidden as $key => $value) {
echo "$key => $value\n"; // 0 => 123, 1 => 654, etc.
}
// Directly access single item:
echo $hidden[3]; // zyg
}
?>

Categories