I'm trying to batch update a table by an ID
My controller:
if(customCompute($this->data['student'])) {
$studentextendID = $this->data['student']->studentextendID;
$this->data['students'] = $this->studentextend_m->get_studentextend(array('studentextendID' => $studentextendID));
} else {
$this->data['students'] = [];
}
$post = $this->input->post();
for($i=0; $i < count($post['subject']); $i++) {
$studentExtendArray[] = array(
'studentextendID' => $studentextendID,
'studentID' => $studentID,
'subject' => $post['subject'][$i],
'subjectng' => $post['subjectng'][$i],
'subjectlg' => $post['subjectlg'][$i],
'subjectcre' => $post['subjectcre'][$i],
);
$this->db->update_batch('studentextend', $studentExtendArray, 'studentextendID');
}
My Model
function get_studentextend($array=NULL, $signal=FALSE) {
$query = parent::get($array, $signal);
return $query;
}
Array Output:
Array (
[0] => Array
(
[studentextendID] => 143
[studentID] => 97
[subject] =>
[subjectng] => 5235
[subjectlg] => 5231
[subjectcre] => 523155
)
[1] => Array
(
[studentextendID] => 143
[studentID] => 97
[subject] =>
[subjectng] => 2
[subjectlg] => 99
[subjectcre] => 3
) )
As you can see, 'studentextendID' is duplicated on both arrays, when it should be dynamically obtained, for example: 143 and 144, because there are two rows in the table with the same 'studentID'
You can try with change in model
public function update_batchs($table, $data)
{
if ($data) {
return $this->db->update_batch($table, $data, 'studentextendID');
}
}
You are not pass the $studentextendID in for loop.You need to pass this in for loop.
$studentextendID = $this->data['student']->studentextendID;
And also please verify $this->data['student'].
Related
here I save data to the database with multiple rows, I want to retrieve each last id per row, how do I do that?
ex : print_r result when input data.
Array
(
[0] => Array
(
[name] => metode 11
[description] => DESC 1
)
[1] => Array
(
[name] => metode 22
[description] => DESC 2
)
[2] => Array
(
[name] => metode 33
[description] => DESC 1
)
)
in database
id | name | description
1 metode 11 desc 1
2 metode 22 desc 2
3 metode 33 desc 3
after finished input I want to take each id
and this my code
$data = array();
$numrow = 1;
foreach ($sheet as $row) {
if ($numrow > 1) {
array_push($data, array(
'name' => $row['A'],
'description' => $row['B'],
));
}
$numrow++;
}
$this->db->insert_batch('my_tabel', $data);
$myid =$this->db->insert_id();
//after insert i retrieve id using last_id() function, however, only last id is fetched, i want to fetch each id
$data_1 = array();
$numrow2 = 1;
foreach ($sheet as $row) {
if ($numrow2 > 1) {
array_push($data_1, array(
'id_last' => $myid,
'id' => $row['E'],
'barang' => $row['F'],
));
}
$numrow2++;
}
i want like this :
Array
(
[0] => Array
(
[last_id] => 1
[id] => 33
[barang] => ccc
)
[1] => Array
(
[last_id] => 2
[id] => 44
[barang] => dd
)
[2] => Array
(
[last_id] => 3
[id] => 55
[barang] => eee
)
)
thanks in advance for those who have answered
I hope what I said was clear enough
Why not insert it row by row instead of a batch?
Build a dictionary from each insert to pair it back later on.
$data = array();
$numrow = 1;
foreach ($sheet as $row) {
if ($numrow > 1) {
array_push($data, array(
'name' => $row['A'],
'description' => $row['B'],
));
}
$numrow++;
}
$array_of_insert_id = array();
foreach ($data as $index => $data_to_insert) {
$this->db->insert('my_tabel', $data_to_insert);
$array_of_insert_id[$index] = $this->db->insert_id();
}
$data_1 = array();
$numrow2 = 1;
$counter = 0;
foreach ($sheet as $row) {
if ($numrow2 > 1) {
array_push($data_1, array(
'id_last' => $array_of_insert_id[$counter],
'id' => $row['E'],
'barang' => $row['F'],
));
}
$numrow2++;
$counter++;
}
//table field with input field data array
$table_data = [
'table_field1' => $input_data1,
'table_field2' => $input_data2,
];
//insert data in database
$this->db->insert('table_name',$table_data);
//after insert return id
return $inserted_id = $this->db->insert_id();
I have an array like this
Array
(
[0] => Array
(
[GRN_id] => 1
[flag_status] => 1
[array_indv_count] => 0
[qty] => 1
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
[1] => Array
(
[GRN_id] => 1
[flag_status] => 1
[array_indv_count] => 1
[qty] =>
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
[2] => Array
(
[GRN_id] => 2
[flag_status] => 3
[array_indv_count] => 2
[qty] => 0
[location_RejHoldCmt] =>
[user_id] => 5
[date] => 29-Jul-2020
)
)
This array is passing to the controller for insertion/updation:
$count = count($_POST['flag_status']);
for($i=0; $i < $count; $i++) {
$data[] = array(
'GRN_id'=>$_POST['id'],
'flag_status' => $_POST['flag_status'][$i],
'array_indv_count' => $i,
'qty' => $_POST['qty'][$i],
'location_RejHoldCmt' => $_POST['location_RejHoldCmt'][$i],
'user_id'=>$this->session->userdata('userid'),
'date'=>date('d-M-Y'),
);
}
$this->db->insert_batch('GRN_details', $data);
I need to update the DB if the rows exists in the array based on the three values(GRN_id,flag_status,array_indv_count) and insert if no matches with the same three values. Now the rows are inserting into the db on every execution. My DB structure is like below:
Instead of inserting as a batch, check for each record if it exists according to the conditions. If a record exists according to the conditions update that record else insert as a new record.
$count = count($_POST['flag_status']);
for($i=0; $i < $count; $i++) {
$data = array(
'GRN_id'=>$_POST['id'],
'flag_status' => $_POST['flag_status'][$i],
'array_indv_count' => $i,
'qty' => $_POST['qty'][$i],
'location_RejHoldCmt' => $_POST['location_RejHoldCmt'][$i],
'user_id'=>$this->session->userdata('userid'),
'date'=>date('d-M-Y'),
);
$data = xss_clean($data);
// select from table with conditions
$this->db->select('id')
$this->db->from('GRN_details')
$this->db->where('GRN_id', $data['GRN_id']);
$this->db->where('flag_status', $data['flag_status']);
$this->db->where('array_indv_count', $data['array_indv_count']);
$query = $this->db->get();
if ($query->num_rows() > 0) {
// if there is a match update
$record = $query->row();
$this->db->update('GRN_details', $data, array('id'=> $record->id ));
} else {
// if there is no match insert
$this->db->insert('GRN_details', $data);
}
}
I need to take an array like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 218
)
[1] => Array
(
[county_code] => 54045
[count] => 115
)
[2] => Array
(
[county_code] => 54051
[count] => 79
)
)
And merge all arrays with the same county_code adding the count, like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 333
)
[1] => Array
(
[county_code] => 54051
[count] => 79
)
)
There will be multiple instances of multiple county codes.
Can anyone point me in the right direction?
Try this out:
// your example array
$array = [
[
"county_code" => 54045,
"count" => 218
],
[
"county_code" => 54045,
"count" => 115
],
[
"county_code" => 54051,
"count" => 79
]
];
// intrim step to collect the count.
$intrimArray = [];
foreach( $array as $data ){
$countyCode = $data["county_code"];
if (!$intrimArray[$countyCode]) {
$intrimArray[$countyCode] = $data["count"];
} else {
$intrimArray[$countyCode] = $intrimArray[$countyCode] + $data["count"];
}
}
// build the final desired array using interim array.
$finalArray = [];
foreach($intrimArray as $countyCode => $totalCount) {
array_push($finalArray, [
"county_code" => $countyCode,
"count" => $totalCount
]);
}
var_dump($finalArray);
As promised:
<?php
$initial_array = [
['country_code' => 54045, 'count' => 218],
['country_code' => 54045, 'count' => 115],
['country_code' => 54051, 'count' => 79],
];
$synth = [];
foreach ($initial_array as $sa) { # $sa: subarray
if (!isset($synth[$sa['country_code']])) {
$synth[$sa['country_code']] = 0;
}
$synth[$sa['country_code']] += $sa['count'];
}
print_r($synth); # Synthesis array: keys are country codes, values are cumulative counts.
# If you need the same format for both the initial and synthesis arrays, then continue with this:
$synth2 = [];
foreach ($synth as $k => $v) {
$synth2[] = ['country_code' => $k, 'count' => $v];
}
print_r($synth2);
?>
A fiddle for this code: https://3v4l.org/M8tkb
Best regards
In my input array, I have multiple rows with a userTag of All, but I only want a maximum of one. Other rows my have duplicated userTag values (such as Seeker), but extra All rows must be removed.
$input = [
0 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 70],
1 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => 14],
2 => ['userTag' => 'All', 'fbId' => 10210118553469338, 'price' => null],
3 => ['userTag' => 'Seeker', 'fbId' => 10207897577195936, 'price' => 65],
6 => ['userTag' => 'Seeker', 'fbId' => 709288842611719, 'price' => 75],
17 => ['userTag' => 'Trader', 'fbId' => 2145752308783752, 'price' => null]
];
My current code:
$dat = array();
$dat2 = array();
foreach ($input as $key => $value)
{
$i = 0;
$j = 0;
if (count($dat) == 0) {
$dat = $input[$key];
$i++;
} else {
if ($input[$key]['userTag'] == "All") {
if ($this->check($input[$key]['fbId'], $dat) == false) {
$dat[$i] = $input[$key];
$i++;
}
} else {
$dat2[$j] = $input[$key];
$j++;
}
}
}
$data = array_merge($dat, $dat2);
return $data;
The check() function:
public function check($val, $array) {
foreach ($array as $vl) {
if ($val == $array[$vl]['fbId']) {
return true;
break;
}
}
return false;
}
You can try something simple like this:
$data = [];
foreach($input as $key => $value)
{
$counter = 0;
if($value['userTag'] =="All"){
if($counter == 0 ) {//test if is the first userTag == All
$counter = 1;//increment the counter so the if doesn't trigger and the value isn't appended
$data[] = $value;//add it to the array
}
} else {
$data[] = $value;//keep the rest of the values
}
}
return $data;
You can use the below code, This will remove all duplicate values from your array.
$arr = array_map("unserialize", array_unique(array_map("serialize", $arr)));
UPDATED ANSWER
The updated answer below is the accurate solution asked in the question which helps with All rows data too.
$temp = array();
foreach($arr as $key => $val) {
if ($val['userTag'] == "All" && empty($temp)) {
$temp[$key] = $arr[$key];
unset($arr[$key]);
}
else if ($val['userTag'] == "All") {
unset($arr[$key]);
}
}
$arr = array_merge($arr, $temp);
Check this code. Perfectly working.
$n_array = array();$i=0;
foreach($array as $row){
if($row['userTag']=="All"){
if($i==0){
$n_array[]=$row;
$i=1;
}
}
else $n_array[]=$row;
}
echo "<pre>";print_r($n_array);
Result
Array
(
[0] => Array
(
[userTag] => All
[fbId] => 10210118553469338
[fName] => Danish
[lName] => Aftab
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/22491765_10210410024475931_8589925114603818114_n.jpg?oh=7fa6266e7948ef2d218076857972f7e0
[subsType] => gold
[user_visible] => 0
[distance] => 0.01
[advising] => 0
[avgRate] => 4
[totalReview] => 2
[us_seeker_type] => new
[price] => 70
)
[1] => Array
(
[userTag] => Seeker
[fbId] => 10207897577195936
[fName] => Saq
[lName] => Khan
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/21151741_10207631130774942_8962953748374982841_n.jpg?oh=f5e5b9dff52b1ba90ca47ade3d703b01
[subsType] => gold
[user_visible] => 0
[background] =>
[topic] =>
[distance] => 0.01
[advising] => 0
[avgRate] => 0
[totalReview] => 0
[us_seeker_type] => new
[price] => 65
)
[2] => Array
(
[userTag] => Seeker
[fbId] => 709288842611719
[fName] => Muhammad
[lName] => Hasan
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20264704_681395725401031_2098768310549259034_n.jpg?oh=36db5b6ed60214088750794d4e3aa3e6
[subsType] => gold
[user_visible] => 0
[distance] => 0.02
[advising] => 0
[avgRate] => 0
[totalReview] => 0
[us_seeker_type] => new
[price] => 75
)
[3] => Array
(
[userTag] => Trader
[fbId] => 2145752308783752
[fName] => Jawaid
[lName] => Ahmed
[imageUrl] => https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/20992899_2068273703198280_4249128502952085310_n.jpg?oh=6df0be6ced405dd66ee50de238156183
[subsType] => basic
[user_visible] => 0
[advising] => 0
[distance] => 0
[avgRate] => 0
[totalReview] => 0
[utr_trader_type] => new
[price] =>
)
)
To keep only the first occurrence of the All row, build an array where All is used as a first level key in the result array. If the row isn't an All row, just keep using its original numeric key. Using the ??= "null coalescing assignment operator", you ensure that only the first All value is stored and all subsequently encountered All rows are ignored.
Code: (Demo)
$result = [];
foreach ($array as $key => $row) {
$result[$row['userTag'] === 'All' ? 'All' : $key] ??= $row;
}
var_export($result);
If you don't want to have the All key for later processing reasons, you can replace it by un-setting then re-pushing it into the array (after finishing the loop).
$result[] = $result['All']; // or unshift($result, $result['All']) to the start of the array
unset($result['All']);
Query run is based on 2 id, however I get one output value
Input:
public function get_place_order_category($id)
{
/* $id = 1,2;*/
$ids = explode(',',$id);
foreach($ids as $catid)
{
$this->db->where('product_id =',trim($catid));
$query = $this->db->get('products');
return $query->result_array();
}
}
Output:
Array
(
[0] => Array
(
[product_id] => 12
[product_name] => Product1
[product_code] => pro12345
[product_price] => 200.00
[product_newprice] => 0.00
[size] => 0-6M , 0-9M ,9-12M
[product_front] => 1446200664.JPG
[product_back] => 14462006641.JPG
[product_left] => 14462006642.JPG
[product_right] => 14462006643.JPG
[product_description] =>
[styling_tips] =>
[category_id] => 62
[user_id] => 5
[status] => 1
[parent_id] => 42
[qty] => 4
[promo_id] => 0
[etc4] => 0
[etc5] => 0
)
)
You can use one global array and add result arrays to it. Try this:
public function get_place_order_category($id)
{
/* $id = 1,2;*/
//first test here what comes in $id
echo $id."<br/>";
$ans_arr = array();
$ids = explode(',',$id);
/*test here too whats actually happens after explode weather
arrayhas generated and what are the element of it */
echo "<pre>";print_r($ids);echo "<br/>";
foreach($ids as $catid)
{
$this->db->where('product_id =',trim($catid));
$query = $this->db->get('products');
$ans_arr[] = $query->result_array();
}
return $ans_arr;
}