I have an array that I will insert into the item table, here I use multiple inserts
Array
(
[0] => Array
(
[id_service] => 2
[tracking_number] => RJC219384044389234035
)
[1] => Array
(
[id_service] => 1
[tracking_number] => RJC749944771469498146
)
)
in the item table, there is already id_service: 2
how to make validation, when one of the input is already in the item table, then all the input is false so it fails?
my code
public function nyobain()
{
$resi = $this->input->post('kode'); //tracking_number
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld); //get 'id_service' where tracking_number
// $db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
// foreach ($db $key) {
// $temp=array($key->id_service);
// }
// how to cek ? if id_service already in the item table
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = array(
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
);
$this->db->insert('tabel_items', $data_insert);
}
echo json_encode($data);
}
You can use in_array to achieve this
public function nyobain(){
$resi = $this->input->post('kode');
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld);
$db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
if(isset($data) && $data !== ''){//check if $data has a value and it not null
if (in_array($data ,$db, true)) {
return $data.'already exists in the DB!';
}else{
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = [
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
];
$this->db->insert('tabel_items', $data_insert);
}
return json_encode($data);
}
}
}
Related
I have following foreach loop
$selectedids = "1255;1256;1257";
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$output1 = $idstand++;
echo "<li>product_id_$output1 = $item,</li>";
}
I want to add the output of the above loop inside following associative array
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge
)
So that the final array will look like this;
$paramas = array(
'loginId' => $cred1,
'password' => $credpass1,
'orderId' => $orderid,
'offer' => $offerid,
'shipid' => $shipcharge,
'product1_id' => 1255,
'product2_id' => 1256,
'product3_id' => 1257,
)
I tried creating following solution but its not working for me
$selectedids = $boughtitem;
$selectedidsarr = explode(';', $selectedids);
$idstand = '1';
foreach ($selectedidsarr as $item) {
$idoutput1 = $idstand++;
$paramas [] = array (
'product$idoutput1_id' => $item,
);
}
Need advice.
You don't need to define a new array, just set the key of the current array to the value you want, in the form of $array[$key] = $value to get an array that looks like [$key=>$value], or in your case...
$paramas['product' . $idoutput1 . '_id'] = $item;
I need to merge 3 associative arrays into a single associative array with unique usernames
My 3 arrays look like this: (var_export)
acceptedArray
array ( 'user1' => 1, 'user2' => 1, 'user3' => 1, )
pendingArray
array ( 'user1' => 1, 'user3' => 2, 'user15' => 3, )
deniedArray
array ( 'user1' => 1, 'user15' => 22, 'user20' => 5, )
every array is a array_count_values of a query fetch.
i need to have an output like this:
$return = [
['username' => user1, 'accepted' => 1, 'pending' => 3 , 'denied' => 1]
['username' => user2, 'accepted' => 1, 'pending' => 4]
];
i tried this (yes, completely off):
foreach ($acceptedUsers as $key => $value) {
$return[] = array('username' => $key, 'accepted' => $value);
}
foreach ($pendingUsers as $key => $value) {
$return[] = array('username' => $key, 'pending' => $value);
}
but that's creating duplicates and not appending.
Iterate individual arrays and use the usernames as keys for grouping.
Code: (Demo)
$acceptedUsers = ["user1" => 1, "user2" => 1, "user3" => 1];
$pendingUsers = ["user1" => 3, "user2" => 4, "user5" => 2];
$deniedUsers = ["user1" => 1, "user15" => 4, "user10" => 2];
foreach ($acceptedUsers as $user => $count) {
$result[$user]['accepted'] = $count;
}
foreach ($pendingUsers as $user => $count) {
$result[$user]['pending'] = $count;
}
foreach ($deniedUsers as $user => $count) {
$result[$user]['denied'] = $count;
}
var_export($result);
And if you need the username inside the subarrays, it's probably less convoluted to just loop the groups once more. https://3v4l.org/0rUv5
foreach ($acceptedUsers as $user => $count) {
$grouped[$user]['accepted'] = $count;
}
foreach ($pendingUsers as $user => $count) {
$grouped[$user]['pending'] = $count;
}
foreach ($deniedUsers as $user => $count) {
$grouped[$user]['denied'] = $count;
}
foreach ($grouped as $user => $row) {
$result[] = ['username' => $user] + $row;
}
var_export($result);
Otherwise, make isset() checks in loop 2 and 3. https://3v4l.org/3sstg
foreach ($acceptedUsers as $user => $count) {
$grouped[$user]['username'] = $user;
$grouped[$user]['accepted'] = $count;
}
foreach ($pendingUsers as $user => $count) {
if (!isset($grouped[$user])) {
$grouped[$user]['username'] = $user;
}
$grouped[$user]['pending'] = $count;
}
foreach ($deniedUsers as $user => $count) {
if (!isset($grouped[$user])) {
$grouped[$user]['username'] = $user;
}
$grouped[$user]['denied'] = $count;
}
var_export(array_values($grouped));
or brutal-force the usernames (unconditionally overwrite pre-existing username elements) https://3v4l.org/I1kBu
foreach ($acceptedUsers as $user => $count) {
$grouped[$user]['username'] = $user;
$grouped[$user]['accepted'] = $count;
}
foreach ($pendingUsers as $user => $count) {
$grouped[$user]['username'] = $user;
$grouped[$user]['pending'] = $count;
}
foreach ($deniedUsers as $user => $count) {
$grouped[$user]['username'] = $user;
$grouped[$user]['denied'] = $count;
}
var_export(array_values($grouped));
You can try this code for getting your result
$acceptedArray = array ( 'user1' => 1, 'user2' => 1, 'user3' => 1 );
$pendingArray = array ( 'user1' => 1, 'user3' => 2, 'user15' => 3 );
$deniedArray = array ( 'user1' => 1, 'user15' => 22, 'user20' => 5 );
// Get all distinct username from 3 arrays given
$u1 = array_unique(array_merge(array_keys($acceptedArray),array_keys($pendingArray),array_keys($deniedArray)));
$result = array(); // Initialize the result array
$index=0;
// Loop through each username and check if he has accept value, pending value and denied value
// If value exist, we assign value from array else set it as 0
foreach($u1 as $key => $val){
$tmp = array();
$tmp['username'] = $val;
if(isset($pendingArray[$val]))
$tmp['pending'] = $pendingArray[$val];
else
$tmp['pending'] = 0;
if(isset($acceptedArray[$val]))
$tmp['accepted'] = $acceptedArray[$val];
else
$tmp['accepted'] = 0;
if(isset($deniedArray[$val]))
$tmp['denied'] = $deniedArray[$val];
else
$tmp['denied'] = 0;
$result[$index] = $tmp;
$index++;
}
Demo link is https://3v4l.org/ZnFuX
i have a query inside a for loop that getting the product name of every array element. Now in every element of my array, i have an ID, where i want to concat all product names with the-same shipping_id.
Here i have my array with values like these:
Array name:id with values of:
Array
(
[0] => Array
(
[product_id] => 1
[shipping_id] => 1
)
[1] => Array
(
[product_id] => 2
[shipping_id] => 1
)
[2] => Array
(
[product_id] => 1
[shipping_id] => 2
)
)
now i made this code with these:
$first = true;
$temp_ship_id = "";
$product_list = "";
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
// if($first) {
// $temp_ship_id = $product[0][shipping_id];
// $first = false;
// }
// if($product[0][shipping_id] == $temp_ship_id) {
// $product_list .= $productname.";
// } else {
// $product_list .= $productname.";
// //$product_list = "";
// $temp_ship_id = $product[0]->shipping_id;
// }
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}
what am i doing is, i am getting the first shipping id and store it and i made a condition if they are thesame then i go concat the productname but, i see my logic is bad.
Please help me in other way. Something like This line of code to begin with:
foreach ($ids as $product) {
$productname = $this->getproductname($product[0][product_id]);
//code for concat goes here
}
public function getproductname($product_id) {
$product = DB::table('products')->select('product_name')
->where(['products.product_id'=>$product_id])
->first();
return $product->product_name;
}
Adjust below to your actual data, let me know if you have questions.
<?php
$concat = array();
$array = array( array( 'product_id'=>1, 'shipping_id'=>1, 'product_name' => 'a' ), array( 'product_id'=>2, 'shipping_id'=>1, 'product_name' => 'b' ), array( 'product_id'=>3, 'shipping_id'=>2, 'product_name' => 'c' ), array( 'product_id'=>4, 'shipping_id'=>1, 'product_name' => 'd' ) );
foreach( $array as $row ) {
if( isset( $concat[ $row['shipping_id'] ] ) ) {
$concat[ $row['shipping_id'] ] .= ',' . $row['product_name'];
} else {
$concat[ $row['shipping_id'] ] .= $row['product_name'];
}
}
var_dump( $concat );
?>
How to get the first value of element of array in php.
My story board is like this:
I have an array like this:
(
[0] => Array
(
[ID] => 68
[MATERIAL] => I have
[AC] => Try
)
[1] => Array
(
[ID] => 69
[MATERIAL] => It
[AC] => No Surrender
)
)
I want to update some record on my database like this,
foreach element of array,
UPDATE MY TABEL SET MATERIAL = [MATERIAL], AC = [AC] where id= [id]
this is the model named m_admin :
public function update_eir_to_cost($id, $material, $ac) {
$data = array(
"MATERIAL" => $material,
"AC" => $ac);
$this->db->trans_start();
$this->db->where($id);
$this->db->update('tb_repair_detail', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
// generate an error... or use the log_message() function to log your error
echo "Error Updating";
} else {
echo "Alhamdulillah";
}
}
This is the controller :
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
/*forech element
update table using model
*/
}
This will solve your problem:
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
$this->load->model('m_admin');
foreach ($execute as $row) {
$this->m_admin->update_eir_to_cost($row['ID'], $row['MATERIAL'], $row['AC']);
}
}
Right now i got an array which has some sort of information and i need to create a table from it. e.g.
Student{
[Address]{
[StreetAddress] =>"Some Street"
[StreetName] => "Some Name"
}
[Marks1] => 100
[Marks2] => 50
}
Now I want to create database table like which contain the fields name as :
Student_Address_StreetAddress
Student_Address_StreetName
Student_Marks1
Student_Marks2
It should be recursive so from any depth of array it can create the string in my format.
You can use the RecursiveArrayIterator and the RecursiveIteratorIterator (to iterate over the array recursively) from the Standard PHP Library (SPL) to make this job relatively painless.
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '_' . $key;
}
$keys[] = $key;
}
var_export($keys);
The above example outputs something like:
array (
0 => 'Student_Address_StreetAddress',
1 => 'Student_Address_StreetName',
2 => 'Student_Marks1',
3 => 'Student_Marks2',
)
(Working on it, here is the array to save the trouble):
$arr = array
(
'Student' => array
(
'Address' => array
(
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => '100',
'Marks2' => '50',
),
);
Here it is, using a modified version of #polygenelubricants code:
function dfs($array, $parent = null)
{
static $result = array();
if (is_array($array) * count($array) > 0)
{
foreach ($array as $key => $value)
{
dfs($value, $parent . '_' . $key);
}
}
else
{
$result[] = ltrim($parent, '_');
}
return $result;
}
echo '<pre>';
print_r(dfs($arr));
echo '</pre>';
Outputs:
Array
(
[0] => Student_Address_StreetAddress
[1] => Student_Address_StreetName
[2] => Student_Marks1
[3] => Student_Marks2
)
Something like this maybe?
$schema = array(
'Student' => array(
'Address' => array(
'StreetAddresss' => "Some Street",
'StreetName' => "Some Name",
),
'Marks1' => 100,
'Marks2' => 50,
),
);
$result = array();
function walk($value, $key, $memo = "") {
global $result;
if(is_array($value)) {
$memo .= $key . '_';
array_walk($value, 'walk', $memo);
} else {
$result[] = $memo . $key;
}
}
array_walk($schema, 'walk');
var_dump($result);
I know globals are bad, but can't think of anything better now.
Something like this works:
<?php
$arr = array (
'Student' => array (
'Address' => array (
'StreetAddress' => 'Some Street',
'StreetName' => 'Some Name',
),
'Marks1' => array(),
'Marks2' => '50',
),
);
$result = array();
function dfs($data, $prefix = "") {
global $result;
if (is_array($data) && !empty($data)) {
foreach ($data as $key => $value) {
dfs($value, "{$prefix}_{$key}");
}
} else {
$result[substr($prefix, 1)] = $data;
}
}
dfs($arr);
var_dump($result);
?>
This prints:
array(4) {
["Student_Address_StreetAddress"] => string(11) "Some Street"
["Student_Address_StreetName"] => string(9) "Some Name"
["Student_Marks1"] => array(0) {}
["Student_Marks2"] => string(2) "50"
}
function getValues($dataArray,$strKey="")
{
global $arrFinalValues;
if(is_array($dataArray))
{
$currentKey = $strKey;
foreach($dataArray as $key => $val)
{
if(is_array($val) && !empty($val))
{
getValues($val,$currentKey.$key."_");
}
else if(!empty($val))
{
if(!empty($strKey))
$strTmpKey = $strKey.$key;
else
$strTmpKey = $key;
$arrFinalValues[$strTmpKey]=$val;
}
}
}
}