Related
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 had simple key in the totalwithouttax with 3000, totaltax with 10 and totalamtincltax with 2000 in my interface.
And I had echo the array, the totaltax and totalamtincltax echo the right value that I key in, But totalwithouttax echo 1000 only and data inserted in database is 1.000000.
Please help me. Thank You.
Controller:
$custTd = $post['id'];
$custMame = $post['name'];
$custEmail = $post['email'];
$custAddr = $post['address'];;
$custTel = $post['telno'];
$remarks = $post['remark'];
$paymentOption = $post['options'];
$promoCode = $post['promo_code'];
$arraySize = count($post['totalwithouttax']);
for($i=0; $i<$arraySize; $i++){
$totalWithoutTax = $post['totalwithouttax'][$i]; //$post['totalwithouttax'];
$totalTax = $post['totaltax'][$i]; //$post['totaltax'];
$totalAmtInclTax = $post['totalamtincltax'][$i];//$post['totalamtincltax'];
//MASSAGE DATA TO BE INSERTED TO ARRAY
$orderHeader = array(
'user_id' => $custTd,
'status' => 1,
'cust_name' => $custMame,
'cust_email' => $custEmail,
'cust_addr' => $custAddr,
'cust_tel' => $custTel,
'remarks' => $remarks,
'pay_option' => $paymentOption,
'total_without_tax' => $totalWithoutTax,
'total_tax' => $totalTax, 'total_amt_incl_tax' => $totalAmtInclTax,
'epp_first_payment' => $eppFirstPayment,
);
//INSERT ORDER HEADER
$orderHeaderId = $this->order->InsertOrderHeader($orderHeader);
view:
<tr class="item-details">
<td><span class="rowNumber">1</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'id' => 'item_id',
'class' => 'form-control'
);
echo form_dropdown('item_id[]', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]" min="0.00" /></td>
<td><input type="number" name="weight[]" class="weight" step="any" /></td>
<td><input type="number" name="transportation[]" class="transporation" step="any" /></td>
<td><input type="text" id="gp[]" name="gp[]" value="" /></td>
<td><input type="text" id="discount[]" name="discount[]" value=""/></td>
<td><input type="text" id="unit_price[]" name="unit_price[]" value="" /></td>
<td align="right">
<input type="text" id="totalwithouttax" name="totalwithouttax[]" value="">
</td>
<td align="right">
<input type="text" id="totaltax" name="totaltax[]" value="">
</td>
<td align="right">
<input type="text" id="totalamtincltax" name="totalamtincltax[]" value="">
</td>
</tr><br/>
You are wrong way calling post method
$custTd = $_POST['id'];
$custMame = $_POST['name'];
$custEmail = $_POST['email'];
$custAddr = $_POST['address'];;
$custTel = $_POST['telno'];
$remarks = $_POST['remark'];
$paymentOption = $_POST['options'];
$promoCode = $_POST['promo_code'];
$arraySize = count($post['totalwithouttax']);
for($i=0; $i<=$arraySize; $i++){
$totalWithoutTax = $_POST['totalwithouttax'][$i];
$totalTax = $_POST['totaltax'][$i]; //$post['totaltax'];
$totalAmtInclTax = $_POST['totalamtincltax'][$i];
//MASSAGE DATA TO BE INSERTED TO ARRAY
$orderHeader = array(
'user_id' => $custTd,
'status' => 1,
'cust_name' => $custMame,
'cust_email' => $custEmail,
'cust_addr' => $custAddr,
'cust_tel' => $custTel,
'remarks' => $remarks,
'pay_option' => $paymentOption,
'total_without_tax' => $totalWithoutTax,
'total_tax' => $totalTax,
'total_amt_incl_tax' => $totalAmtInclTax,
'epp_first_payment' => $eppFirstPayment,
);
}
I got 3 constant rows with few columns like Item,Quantity,Weight...... in a row, in my Interface.
When I selected the data in the rows and submit form, only the 3rd row data will be inserted into the database.
I want each rows that contain data insert into the database. Any solution for this? Thank You.
Updated::
I had tried to use the PHP array and below is the updated code.But I had stucked at the foreach part, I want to insert the data into the database.
My View:
<tr class="item-details">
<td><span class="rowNumber">1</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
<tr class="item-details">
<td><span class="rowNumber">2</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
<tr class="item-details">
<td><span class="rowNumber">3</span></td>
<td class="">
<?php
$options = array(
'' => '~Choose An Item~'
);
foreach ($item as $rows){
$options[$rows->id] = $rows->item_name;
}
$select = array(
'name' => 'item_name[]',
'id' => 'item_name',
'class' => 'form-control'
);
echo form_dropdown('item', $options,set_value('item_name'),$select);
?>
</td>
<td class=""><input type="number" class="item-qty" name="qty[]"/></td>
<td><input type="number" name="weight[]" class="weight" /></td>
<td><input type="text" name="promo_code[]" value=""/></td>
<td><input type="text" name="gp[]" value=""/></td>
<td><input type="text" name="discount[]" value=""/></td>
<td><input type="text" name="unit_price[]" value=""/></td>
<td align="right" class="totalwithouttax">0.00</td>
<td align="right" class="totaltax">0.00</td>
<td align="right" class="totalamtincltax">0.00</td>
</tr><br/>
Controller:
//***************** ORDER ITEM ********************
$orderID = 1;
$productId = $this->input->post('product_id');
$itemName = $_POST['item_name'];//$this->input->post('item_name');
$qty = $this-> $_POST['qty'];//input->post('qty');
$weight = $this-> $_POST['weight'];//input->post('weight');
$unitPrice = $_POST['unit_price'];//$this->input->post('unit_price');
$transportationPrice = $this->input->post('transportation_price');
$itemType = $this->input->post('item_type');
$gp = $this-> $_POST['gp'];//input->post('gp');
$tax = $this->input->post('tax');
$amtInclTax = $this->input->post('amt_incl_tax');
$amtWithoutTax = $this->input->post('amt_without_tax');
$taxCode = $this->input->post('tax_code');
$orderItems = array (
'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => $itemName ,
'qty' => $qty ,
'weight' => $weight ,
'unit_price' => $unitPrice ,
'transportation_price' => 0 ,
'item_type' => 'GOLD' ,
'gp' => $gp,
'discount' => $discount,
'amt_without_tax' => 10,
'tax' => 20 ,
'amt_incl_tax' => 30,
'tax_code' => 40 ,
);
echo '<pre>'; print_r($orderItems); echo '</pre>';
foreach($itemName as $key => $iN){
//stuck at here
}
$orderHeaderId = $this->order->InsertItemData($orderHeaderId,$orderHeader,$orderItems);
Model:
public function InsertItemData($orderHeaderId,$orderHeader,$orderItems){
//take order_id from 'order' table //from InsertData(model) function
$orderHeaderId = $this->InsertData($orderHeader);
// Inserting Order Item
if($orderItems){
$this->db->insert_batch('order_items', $orderItems);
}
}
First make your all 3 portion of HTML form input name array like
<input type="number" class="item-qty" name="qty[]"/>
<input type="number" name="weight" class="weight[]" />
...
Then loop your data array as
$qty = $this->input->post('qty', TRUE);
$weight = $this->input->post('weight', TRUE);
$orderItems = array();
for ($i = 0; $i < count($qty); $i++) {
if ($qty[$i]) {
$orderItems[] = array (
'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => 'TEST' ,
'qty' => $qty[$i] ,
'weight' => $weight[$i]
...
);
}
}
And now you may use insert_batch method as
if ($orderItems) {
$this->db->insert_batch('table_name', $orderItems);
}
You could modify each of the codes like below.
Controller :
$orderID = 1;
$productId = $this->input->post('product_id');
$itemName = $_POST['item_name'];//$this->input->post('item_name');
$qty = $this-> $_POST['qty'];//input->post('qty');
$weight = $this-> $_POST['weight'];//input->post('weight');
$unitPrice = $_POST['unit_price'];//$this->input->post('unit_price');
$transportationPrice = $this->input->post('transportation_price');
$itemType = $this->input->post('item_type');
$gp = $this-> $_POST['gp'];//input->post('gp');
$tax = $this->input->post('tax');
$amtInclTax = $this->input->post('amt_incl_tax');
$amtWithoutTax = $this->input->post('amt_without_tax');
$taxCode = $this->input->post('tax_code');
$orderItems = array();
for ($i = 0; $i < count($qty); $i++) {
if ($qty[$i]) {
$orderItems[] = array (
// 'order_id' => $orderHeaderId ,
'product_id' => 7 ,
'item' => $itemName[$i] ,
'qty' => $qty[$i] ,
'weight' => $weight[$i] ,
'unit_price' => $unitPrice[$i] ,
'transportation_price' => 0 ,
'item_type' => 'GOLD' ,
'gp' => $gp[$i],
'discount' => $discount[$i],
'amt_without_tax' => 10,
'tax' => 20 ,
'amt_incl_tax' => 30,
'tax_code' => 40 ,
);
}
}
$this->order->InsertItemData($orderHeader,$orderItems);
Model :
public function InsertItemData($orderHeader,$orderItems) {
//take order_id from 'order' table //from InsertData(model) function
$orderHeaderId = $this->InsertData($orderHeader);
if($orderItems) {
// append order_id array into each order item
foreach ($orderItems as $key => $item) {
$orderItems[$key] = array('order_id' => $orderHeaderId) + $orderItems[$key];
}
// Inserting Order Item
$this->db->insert_batch('order_items', $orderItems);
}
}
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>
Problem:
I am trying to generate a custom HTML form with help of values in an array using PHP.
The PHP code ($row['Key'] will contain W, B and R):
$numbers[$row['Key']] = array (
'C' =>
array (
'BO' => $row['BO'],
'BT' => $row['BT']),
'D' =>
array (
'MF' => $row['MF'],
'MT' => $row['MT'])
);
Array produced with PHP:
Array
(
[W] => Array
(
[C] => Array
(
[BO] => 36
[BT] => 63
)
[D] => Array
(
[MF] => 54
[MT] => 63
)
)
[B] => Array
(
[C] => Array
(
[BO] => 60
[BT] => 105
)
[D] => Array
(
[MF] => 90
[MT] => 105
)
)
[R] => Array
(
[C] => Array
(
[BO] => 12
[BT] => 21
)
[D] => Array
(
[MF] => 18
[MT] => 24
)
)
)
The outcome should look like the following. Notice the combination of W/B/R and BO/BT/MF/MT.
<table>
<tbody>
<tr>
<td>W</td>
<td><input type="text" name="WBO" id="WBO" value="36"></td>
<td><input type="text" name="WBT" id="WBT" value="63"></td>
<td><input type="text" name="WMF" id="WMF" value="54"></td>
<td><input type="text" name="WMT" id="WMT" value="63"></td>
</tr>
<tr>
<td>B</td>
<td><input type="text" name="BBO" id="BBO" value="60"></td>
<td><input type="text" name="BBT" id="BBT" value="105"></td>
<td><input type="text" name="BMF" id="BMF" value="90"></td>
<td><input type="text" name="BMT" id="BMT" value="105"></td>
</tr>
<tr>
<td>R</td>
<td><input type="text" name="RBO" id="RBO" value="12"></td>
<td><input type="text" name="RBT" id="RBT" value="21"></td>
<td><input type="text" name="RMF" id="RMF" value="18"></td>
<td><input type="text" name="RMT" id="RMT" value="24"></td>
</tr>
</tbody>
</table>
http://php.net/manual/en/control-structures.foreach.php
without using 3 foreach loops
$var = print_r($numbers, true);
$table = preg_replace_callback(
"{.*?[^ ][ ]{4}\[(\S+)\].*?[^ ][ ]{8}\)}s",
"func",
$var);
$table= preg_replace('{\n[^<].*}','',$table);
echo "<table>{$table}</table>";
function: (count space to find array level)
function func($matches)
{
$table='';
$k=$matches[1];
$t=$matches[0];
$tr = preg_replace('{.*?[^ ][ ]{20}\[(\S+)\].*?=>.*?(\S+)}s',PHP_EOL."<td><input type='text' id='{$k}$1' name='{$k}$1' value='$2'></td>",$t);
$table .= "<tr>".PHP_EOL;
$table .= "<td>{$k}<td>{$tr}".PHP_EOL;
$table .= "</tr>".PHP_EOL;
return $table;
}
echo
<table><tr>
<td>W<td>
<td><input type='text' id='WBO' name='WBO' value='36'></td>
<td><input type='text' id='WBT' name='WBT' value='63'></td>
<td><input type='text' id='WMF' name='WMF' value='54'></td>
<td><input type='text' id='WMT' name='WMT' value='63'></td>
</tr>
<tr>
<td>B<td>
<td><input type='text' id='BBO' name='BBO' value='60'></td>
<td><input type='text' id='BBT' name='BBT' value='105'></td>
<td><input type='text' id='BMF' name='BMF' value='90'></td>
<td><input type='text' id='BMT' name='BMT' value='105'></td>
</tr>
</table>
Should be fairly easy to step through this array with foreach().
[ghoti#pc ~]$ cat doit.php
#!/usr/local/bin/php
<?php
printf("<table>\n <tbody>\n");
$numbers=array(
'W' => array(
'C' => array( 'BO' => 36, 'BT' => 63),
'D' => array( 'MF' => 54, 'MT' => 63),
),
'B' => array(
'C' => array( 'BO' => 60, 'BT' => 105),
'D' => array( 'MF' => 90, 'MT' => 105),
),
);
$fmt1 = "\t<tr>\n"
. "\t\t<td>%s</td>\n"
. "%s"
. "\t</tr>\n";
$fmt2 = "\t\t<td><input type='text' name='%s%s' id='%s%s' value='%s'></td>\n";
foreach ($numbers as $index1 => $line1) {
foreach ($line1 as $index2 => $line2) {
foreach ($line2 as $index3 => $value) {
$output .= sprintf($fmt2, $index1, $index3, $index1, $index3, $value);
}
}
printf($fmt1, $index1, $output);
$output = "";
}
printf(" </tbody>\n</table>\n");
And the output:
[ghoti#pc ~]$ ./doit.php
<table>
<tbody>
<tr>
<td>W</td>
<td><input type='text' name='WBO' id='WBO' value='36'></td>
<td><input type='text' name='WBT' id='WBT' value='63'></td>
<td><input type='text' name='WMF' id='WMF' value='54'></td>
<td><input type='text' name='WMT' id='WMT' value='63'></td>
</tr>
<tr>
<td>B</td>
<td><input type='text' name='BBO' id='BBO' value='60'></td>
<td><input type='text' name='BBT' id='BBT' value='105'></td>
<td><input type='text' name='BMF' id='BMF' value='90'></td>
<td><input type='text' name='BMT' id='BMT' value='105'></td>
</tr>
</tbody>
</table>
[ghoti#pc ~]$
this?
echo "<table><tbody>";
foreach((array)$numbers as $key=>$val) {
echo "<tr><td>".$key."</td>";
foreach((array)$val as $key2=>$val2) {
foreach((array)$val2 as $key3=>$val3) {
echo '<td><input type="text" name="'.$key.$key3.'" id="'.$key.$key3.'" value="'.$val3.'"></td>';
}
}
echo "</tr>";
}
echo "</tbody></table>";
Check this code dude.
<table>
<tbody>
<?php
foreach($numbers as $key=>$sarray){
echo "<tr>";
echo "<td>$key</td>";
foreach($sarray as $key1=>$sarray1){
foreach($sarray1 as $fname=>$fvalue){
echo '<td><input type="text" name="'.$fname.'" id="'.$fname.'" value="'.$fvalue.'"></td>';
}
}
echo "</tr>";
}
?>
</tbody>
</table>