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
Related
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>
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);
}
I am Inserting a multiple form input data in to database using Codeigniter.
I have this post input array:
Array
(
[subject_id] => Array
(
[0] => 1
[1] => 1
)
[question] => Array
(
[0] => test
[1] => test2
)
[option1] => Array
(
[0] => test
[1] => test2
) )
I don't get that how do i convert this array to insert How to insert this array using Insert batch.
$this->db->insert_batch('mytable', $data);
This is the form code which i use for posting the data:
<form method="post">
<input type="text" name="subject_id[]" >
<input type="text" name="question[]" >
<input type="text" name="record[]" >
// Down side Part is appended when user want to add more question
<input type="text" name="subject_id[]" >
<input type="text" name="question[]" >
<input type="text" name="record[]" >
<input type="submit" name="submit" >
</form>
Below is the Array format which i want.
$data = array(
array(
'subject_id' => 'My title' ,
'question' => 'My Name' ,
'option1' => 'My date'
),
array(
'subject_id' => 'Another title' ,
'question' => 'Another Name' ,
'option1' => 'Another date'
)
);
<?php
$i = 0;
foreach($subject_id as $key=>$val)
{
$data[$i]['subject_id'] = $val;
$data[$i]['question'] = $question[$key];
$data[$i]['option1'] = $record[$key];
$i++;
}
$this->db->insert_batch('mytable', $data);
?>
Try like below:Assume $records is an array that you want to insert.
foreach ($records as $record)
{
for ($i=0; $i < count($record); $i++)
{
$data[$i]['subject_id'] = $record['subject_id'][$i];
$data[$i]['question'] = $record['question'][$i]
$data[$i]['option1'] = $record['option1'][$i];
}
}
Then
$this->db->insert_batch('mytable', $data);
I have a multidimensional array like this:-
$data = array (
'SalaryHeadName' =>
array (
0 => 'Basic',
1 => 'PF',
),
'SalaryHeadType' =>
array (
0 => 'CR',
1 => 'DR',
),
'Amount' =>
array (
0 => 6000,
1 => 400,
),
)
how to change it into html table report like by using foreach loop or for loop thank in advance.
This is not general, its specific to your problem.
$data = array('SalaryHeadName'=>array(0=>'Basic',1=>'PF'),'SalaryHeadType'=>array(0=>'CR',1=>'DR'),'Amount'=>array(0=>6000,1=>400));
$array_keys = array_keys($data);
<table border="1">
<thead>
<?php foreach ($array_keys as $key) {?>
<th><?php echo $key ?></th>
<?php } ?>
</thead>
<tbody>
<?php for ($i=0; $i<count($data['SalaryHeadName']);$i++) {?>
<tr>
<td><?php echo $data['SalaryHeadName'][$i] ?></td>
<td><?php echo $data['SalaryHeadType'][$i] ?></td>
<td><?php echo $data['Amount'][$i] ?></td>
</tr>
<?php } ?>
</tbody>
</table>
I hope this is what you want,
<?php
$data = array(
'SalaryHeadName' => array(
0 => 'Basic',
1 => 'PF'
) ,
'SalaryHeadType' => array(
0 => 'CR',
1 => 'DR'
) ,
'Amount' => array(
0 => 6000,
1 => 400
)
);
?>
<table border="1" cellpadding="10">
<?php
foreach($data as $key => $value)
{
echo "<tr><td>$key</td>";
foreach($value as $value1)
{
echo "<td>$value1</td>";
}
echo "</tr>";
}
?>
</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>