A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 1539
Backtrace: File: D:\xampp\htdocs\visio\application\models\projectmodel.php
Line: 56
Function: insert_batch
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Array' at line 1
INSERT INTO paymentsize () VALUES ('8'), ('2017-06-07'), ('Residential'), ('L'), ('120'), ('200'), ('10000'), ('15000'), ('30'), ('12000'), ('40'), ('1000'), ('60'), ('125000'), ('10'), ('10000'), ('15000'), ('20000'), Array
Filename: D:/xampp/htdocs/visio/system/database/DB_driver.php
Line Number: 691
My Controller is:
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
My Model is:
public function add_payment($array)
{
// echo "<pre>";
// print_r($array);
// exit();
return $this->db->insert_batch('paymentsize',$array);
}
My View is:
<tbody>
<input type="hidden" name="pro_id[]" value="<?= $project->pro_id; ?>" >
<tr>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label" style="margin-top: -10px;">Date</label>
<input type="date" name="date_add[]" value="<?php echo date('Y-m-d'); ?>" class="form-control" >
<span class="material-input"></span>
</div>
</div>
</td>
<td width="14%">
<div class="col-lg-10">
<div class="form-group form-black label-floating is-empty">
<label class="control-label">Plot Category</label>
<select name="category[]" class="form-control">
<option> </option>
<option>Residential</option>
<option>Commercial</option>
</select>
<span class="material-input"></span>
</div>
</div>
</td>
<td>
if i use print_r it shows all array elements with respective Values.. but it is not inserting in DB Table..
my view has a table with 17 text fields... i just mention few for an Example...
waiting for help.... :)
Thank you in advance...
Change your controller as following code,
public function store_payment()
{
$post = array();
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
for($i = 0; $i < $count; $i++){
$post = array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($post);
}
You used $post for two purpose, change your controller codes as following code:
public function store_payment()
{
$post = $this->input->post(NULL,TRUE);
$count=count($this->input->post('pro_id'));
echo CI_VERSION;
$data = array();
for($i = 0; $i < $count; $i++){
$data []= array(
'pro_id' => $post['pro_id'][$i],
'date_add' => $post['date_add'][$i],
'category' => $post['category'][$i],
'type' => $post['type'][$i],
'size' => $post['size'][$i],
'counts' => $post['counts'][$i],
'booking' => $post['booking'][$i],
'confirmation' => $post['confirmation'][$i],
'confirm_days' => $post['confirm_days'][$i],
'allocation' => $post['allocation'][$i],
'allocate_days' => $post['allocate_days'][$i],
'm_installment' => $post['m_installment'][$i],
'month' => $post['month'][$i],
'y_instalment' => $post['y_instalment'][$i],
'halfyear' => $post['halfyear'][$i],
'leveling' => $post['leveling'][$i],
'demarcation' => $post['demarcation'][$i],
'possession' => $post['possession'][$i]
);
}
$this->projects->add_payment($data);
}
Related
I'm a new with PHP Array and have a form that input multiple parent-child data and save into an array. HTML will be something like this:
<ul>
<li><input type="text" name="group[0][name]" placeholder="Group name">
<ul>
<li>
<p>Member #1</p>
<input type="text" name="group[0][member][0][name]" placeholder="Name">
<input type="text" name="group[0][member][0][age]" placeholder="Age">
</li>
<li>
<p>Member #2</p>
<input type="text" name="group[0][member][1][name]" placeholder="Name">
<input type="text" name="group[0][member][1][age]" placeholder="Age">
</li>
</ul>
</li>
<li><input type="text" name="group[1][name]" placeholder="Group name">
<ul>
<li>
<p>Member #1</p>
<input type="text" name="group[1][member][0][name]" placeholder="Name">
<input type="text" name="group[1][member][0][age]" placeholder="Age">
</li>
</ul>
</li>
</ul>
PHP code:
$output = array();
$i = 0;
foreach ( $_POST['group'] as $group ) {
$members = array();
$m = 0;
foreach ( $_POST['group'][$i]['member'] as $name ) {
$members[$i][] = array(
'name' => $name,
'age' => $_POST['group'][$i]['member'][$m]
);
$m++;
}
$output[] = array(
'group_name' => $_POST['group'][$i]['name'],
'members' => $members[$i]
);
$i++;
}
var_dump( $output );
And I got this result:
array (size=2)
0 =>
array (size=2)
'group_name' => string 'Group 1' (length=7)
'members' =>
array (size=2)
0 =>
array (size=2)
...
1 =>
array (size=2)
...
1 =>
array (size=2)
'group_name' => string 'Group 2' (length=7)
'members' =>
array (size=1)
0 =>
array (size=2)
...
Can't get the member names and ages to be submitted into array. Can somebody help me? And sorry if I didn't explain this correctly. Thanks!
You have to process down the heirarchy, using the new arrays created by the foreach loop is also easier to understand than going back to the master array like you woudl have to in a for loop
$output = [];
foreach ( $_POST['group'] as $group ) {
$mem = []; // init the members each time you start a new group
foreach ( $group['member'] as $member) {
$mem[] = ['name' => $member['name'], 'age' => $member['age']];
}
$output[] = [ 'group_name' => $group, 'members' => $mem ];
}
I have a problem in inserting array in the database in Codeigniter, I tried following way but it gives an error "Message: Illegal string offset 'year'", "Message: Illegal string offset 'month'" and so on..., I really confused about how to solve this, please help.
this is the form:
<form action="<?php echo base_url();?>hr/Home/store_attendance" method="post"
id="student_attendance_entry">
<input type="hidden" name="year" value="<?php echo $year; ?>" />
<input type="hidden" name="month" value="<?php echo $month; ?>" />
<?php foreach($staffs as $staff): ?>
<table class="table table-striped table-bordered table-hover attendance_entry"
style="border:initial;border: 1px solid #ddd;" id="sample_editable_2">
<thead>
<tr>
<th style="width: 50px !important;">شماره</th>
<th align="center" style="width:auto%">آی دی</th>
<th align="center" style="width:15%">نام</th>
<th align="center" style="width:15%;"> ولد</th>
<th align="center" style="width:auto">حاضر</th>
<th align="center" style="width:auto">غیر حاضر</th>
<th align="center" style="width:auto">توضیحات</th>
</tr>
</thead>
<tbody>
<?php $a=1; foreach($staffs as $st):?>
<tr>
<td align="center" style="font-size: 11px"><?php echo $a;?></td>
<td align="center" style="font-size: 11px"><?php echo $st['s_id'];?></td>
<td align="center"><?php echo $st['dari_name'];?></td>
<td align="center"><?php echo $st['dari_fName'];?></td>
<td>
<input type="number" min="0" class="form-control" name="total_present_day[]"
value="<?php if($st['total_present']==null){echo '';}else{ echo $st['total_present'];}?>"
data="<?php echo $a;?>">
<input type="hidden" name="salary_type[]" id="salary_type" value="<?php echo $st['salary_type']?>">
</td>
<td>
<input type="number" min="0" class="form-control" name="total_absent_day[]"
value="<?php if($st['absent']==null){echo '';}else{ echo $st['absent'];}?>"
data="<?php echo $a;?>">
<input type="hidden" class="form-control" name="staff_id[]" value="<?php echo $st['s_id'];?>">
</td>
<td>
<textarea min="0" class="form-control" name="memo[]"
colspan='3' rowspan="1"
data="<?php echo $a;?>"><?php if($st['memo']==null){echo '';}else{ echo $st['memo'];}?></textarea>
</td>
</tr>
<?php $a++;endforeach;?>
</tbody>
</table>
<?php endforeach; ?>
<br>
<div class="form-actions right">
<a href="<?php echo base_url();?>student/school/attendance" class="btn default" data-dismiss="modal"><i
class="fa fa-close"></i> بستن</a>
<input type="submit" name="save" class="btn blue" value="ذخیره" />
</div>
this is the controller:
public function store_attendance()
{
$data=array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staff_id' => $this->input->post('staff_id'),
'total_present_day' => $this->input->post('total_present_day'),
'total_absent_day'=>$this->input->post('total_absent_day'),
'salary_type'=>$this->input->post('salary_type'),
'memo'=>$this->input->post('memo')
);
$this->dd($data);
// $this->dd($class);
$insert_att = $this->stuff_model->add_staff_attendance($data);
// var_dump($insert_att);
if($insert_att)
{
echo redirect(base_url().'hr/register_employee_attendance');
}
}
this is the model:
public function add_staff_attendance($data)
{
$this->db->trans_begin();
foreach ($data['total_present_day'] as $key => $value) {
{
$dataToSave = array(
'year' => $value['year'],
'month' => $value['month'],
'type_id'=>$value['salary_type'][$key],
'total_present' => $value['total_present_day'][$key],
'absent'=>$value['total_absent_day'][$key],
'memo'=>$value['memo'][$key],
'staf_id' => $value['staff_id'][$key]
);
$this->db->insert('staff_attendance', $dataToSave);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}
}
I called $this->dd($data) in controller and this is the output:
array (
'Total' => 7,
)
array (
'year' => '1400',
'month' => '2',
'staff_id' =>
array (
0 => '3',
),
'total_present_day' =>
array (
0 => '26',
),
'total_absent_day' =>
array (
0 => '0',
),
'salary_type' => '1',
'memo' =>
array (
0 => 'dds',
),
)
And this is the result of echo '<pre>'; print_r($data); echo '</pre>'; In model:
Array
(
[year] => 1400
[month] => 1
[staff_id] => Array
(
[0] => 3
[1] => 1
)
[total_present_day] => Array
(
[0] => 26
[1] => 20
)
[total_absent_day] => Array
(
[0] => 0
[1] => 6
)
[salary_type] => Array
(
[0] => 1
[1] => 1
)
[memo] => Array
(
[0] => asfd
[1] => saef
)
)
Array
(
[year] => 1400
[month] => 1
[staff_id] => Array
(
[0] => 3
[1] => 1
)
[total_present_day] => Array
(
[0] => 26
[1] => 20
)
[total_absent_day] => Array
(
[0] => 0
[1] => 6
)
[salary_type] => Array
(
[0] => 1
[1] => 1
)
[memo] => Array
(
[0] => asfd
[1] => saef
)
)
Your submitted data is structured in a logical, minimalistic, yet irregular fashion. By reconfiguring the name attributes of the form fields in your view, you can largely reduce the lines of processing code in the controller and the model.
Move the hidden fields inside your foeach() loop and declare dynamic indexes. Effectively the named fields would resemble this:
<?php foreach($staffs as $index => $staff) { ?>
<input type="hidden" name="attendance[<?php echo $index; ?>]['year']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['month']">
<input type="number" name="attendance[<?php echo $index; ?>]['total_present']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['type_id']">
<input type="number" name="attendance[<?php echo $index; ?>]['absent']">
<input type="hidden" name="attendance[<?php echo $index; ?>]['staf_id']">
<textarea name="attendance[<?php echo $index; ?>]['memo']"></textarea>
<?php } ?>
The controller needs a validation/sanitization process and some restucturing before blindly passing data to the model. I will not go into the validation/sanitization, but you should iterate the data, and deny it from being saved if ANY of the values are inappropriate.
Controller:
public function store_attendance(): void
{
// Definitely validate and sanitize the rows of data before passing to model.
// This shortcut is for demonstrating how to batch insert
if ($this->stuff_model->add_staff_attendance($this->input->post('attendance'))) {
redirect(base_url() . 'hr/home/register_employee_attendance');
} else {
// reload view and explain what went wrong
}
}
Model:
public function add_staff_attendance(array $data): bool
{
return $this->db->insert_batch('staff_attendance', $data);
}
None of this answer was tested.
To leave the hidden fields outside of the loop, you will need to assemble the rows' values into the correct structure before sending to the model for batch_insertion.
$presentDays = $this->input->post('total_present_day');
if ($presentDay) {
$rows = [];
foreach ($presentDays as $i => $presentDay) {
$rows[] = [
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staf_id' => $this->input->post('staff_id')[$i],
'total_present' => $this->input->post('total_present_day')[$i],
'absent' => $this->input->post('total_absent_day')[$i],
'type_id' => $this->input->post('salary_type')[$i],
'memo' => $this->input->post('memo')[$i]
];
}
if ($this->stuff_model->add_staff_attendance($rows)) {
redirect(base_url() . 'hr/home/register_employee_attendance');
} else {
// reload view and explain what went wrong
}
}
public function add_staff_attendance($data)
{
$this->db->trans_begin();
foreach ($data['total_present_day'] as $key => $value) {
{
$dataToSave = array(
'year' => $data['year'], // this seems to be same for all
'month' => $data['month'], // this seems to be same for all
'type_id' => $value['salary_type'][$key], // please change name='salary_type[]' in your form
'total_present' => $value['total_present_day'][$key], // seems to be an array
'absent' => $value['total_absent_day'][$key], // seems to be an array
'memo' => $value['memo'][$key], // seems to be an array
'staf_id' => $value['staff_id'][$key] // seems to be an array
);
$this->db->insert('staff_attendance', $dataToSave);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}
}
I solved my problem by changing some codes in the controller and model.
controller:
public function store_attendance()
{
$data = array();
$insert_att = 0;
$tst = $this->input->post('total_present_day');
for ($i=0; $i < count($tst); $i++) {
$data = array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staf_id' => $this->input->post('staff_id')[$i],
'total_present' => $this->input->post('total_present_day')[$i],
'absent'=>$this->input->post('total_absent_day')[$i],
'type_id'=>$this->input->post('salary_type')[$i],
'memo'=>$this->input->post('memo')[$i],
);
// var_dump($data);
$this->get_public_data->saveData('staff_attendance', $data);
}
echo redirect(base_url().'hr/home/rgisterAttendance');
}
Model:
public function add_staff_attendance($data)
{
$this->db->insert('staff_attendance', $data);
}
it seems that the error is in the controller, you must go through the array while it is saving.
public function store_attendance()
{
$data=array(
'year' => $this->input->post('year'),
'month' => $this->input->post('month'),
'staff_id' => $this->input->post('staff_id'),
'total_present_day' => $this->input->post('total_present_day'),
'total_absent_day'=>$this->input->post('total_absent_day'),
'salary_type'=>$this->input->post('salary_type'),
'memo'=>$this->input->post('memo')
);
foreach($data as $d):
$insert_att = $this->stuff_model->add_staff_attendance($d);
if($insert_att)
{
echo redirect(base_url().'hr/register_employee_attendance');
}
else
{
echo redirect(base_url().'hr/register_employee_attendance');
}
endforeach;
}
You should try something like it
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',
),
)
When i am using shortcode it prints and error as
Notice: Array to string conversion in /home/nadiaz5/public_html/wp-includes/shortcodes.php on line 345
function ff_register_shortcode(){
$danger="";
$BoxLength=esc_attr( get_option('ff_list_boxes') );
$fedex_feeding= array();
$keys = array('name', 'id', 'max_weight', 'box_weight','length','width','height','inner_length','inner_width','inner_height','type');
for($f=0 ; $f<$BoxLength;$f++){
array_push($fedex_feeding, array(
'name' => get_option('ff_name_'.$f),
'id' => get_option('ff_id_'.$f),
'max_weight' => get_option('ff_max_weight_'.$f),
'box_weight' => get_option('ff_box_weight_'.$f),
'length' => get_option('ff_length_'.$f),
'width' => get_option('ff_width_'.$f),
'height' => get_option('ff_height_'.$f),
'inner_length' => get_option('ff_inner_length_'.$f),
'inner_width' => get_option('ff_inner_width_'.$f),
'inner_height' => get_option('ff_inner_height_'.$f),
'type' => get_option('ff_type_'.$f),
)
);
}
$danger = array();
$BoxLength=esc_attr( get_option('ff_list_boxes') );
for ($i=0; $i < $BoxLength; $i++) {
array_push($danger , $fedex_feeding[$i]);
}
return $danger;
}
add_shortcode('ff_arrays' , 'ff_register_shortcode');
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>