I'm facing a little problem and I don't know is it's possible to achieve it or not. Let me explain :
I have an associative array like this :
Array
(
[res_id] => 104
[subject] => Test
[type_id] => 503
[format] => pdf
[typist] => fefe
[creation_date] => 2017-02-10 14:27:37.236711
[modification_date] => 2017-02-10 14:27:37.236711
[fulltext_result] => 1
[doc_date] => 2017-02-01 00:00:00
[docserver_id] => FASTHD_MAN
[path] => 2017#02#0001##
[filename] => 0008.pdf
[fingerprint] =>
[filesize] => 84979
[status] => VAL
[destination] => DSG
[priority] => 2
[is_multi_docservers] => N
[is_frozen] => N
[tablename] => res_letterbox
[initiator] => COU
[dest_user] => ddaull
[locker_user_id] => fefefef
[locker_time] => 2017-02-13 15:52:25.624521
[confidentiality] => N
[tnl_path] => 2017#02#0001##
[tnl_filename] => 0008.png
)
I want to know if I can use this associative array, in order to make an INSERT TO request ? I want the first part of the array (like res_id, subject) goes to column part for the insertion. The second part of the array (like 104,Test) will go to the values
Thanks in advance for your help, hope I am clear enough..
#Nathan30 try this :
<?php
$arr = array(
"res_id" => 104,
"subject" => "Test",
"type_id" => 503,
"format" => "pdf",
"typist" => "fefe",
"creation_date" => "2017-02-10 14:27:37.236711",
"modification_date" => "2017-02-10 14:27:37.236711",
"fulltext_result" => 1,
"doc_date" => "2017-02-01 00:00:00",
"docserver_id" => "FASTHD_MAN",
"path" => "2017#02#0001##",
"filename" =>" 0008.pdf",
"fingerprint" => "",
"filesize" => 84979,
"status" => "VAL",
"destination" => "DSG",
"priority" => 2,
"is_multi_docservers" => "N",
"is_frozen" => "N",
"tablename" => "res_letterbox",
"initiator" => "COU",
"dest_user" => "ddaull",
"locker_user_id" => "fefefef",
"locker_time" => "2017-02-13 15:52:25.624521",
"confidentiality" => "N",
"tnl_path" => "2017#02#0001##",
"tnl_filename" => "0008.png",
);
echo "<pre>";
print_r($arr);
$column = array();
$values = array();
foreach($arr as $key => $value){
$column[] = $key;
$values[] = $value;
}
now query will be like:
"insert into table values(".implode(',', $column).") values (".implode(',', $values).")";
Related
I'm retrieving some JSON that I am converting to an associative array. The issue that I am having is I am trying to get the email value from the user's who id matches the value that I have already set as a variable.
Here is what the array looks like
Array
(
[object] => list
[data] => Array
(
[0] => Array
(
[object] => pro
[id] => pro_77c9c6a85d814e059a6a2690989bae29
[first_name] => Jane
[last_name] => Doe
[full_name] => Jane Doe
[initials] => JD
[email] => admin#testorg.com
[mobile_number] => 9998761234
[messaging_uuid] => 4547c231c3e7d0ff1796f47b88f166d5
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
[1] => Array
(
[object] => pro
[id] => pro_0fcb8e8610e54c518078db77ced7530e
[first_name] => Robert
[last_name] => Jordan
[full_name] => Robert Jordan
[initials] => RJ
[email] => rj#testorg.com
[mobile_number] => 4547457742
[messaging_uuid] => 0fcb8e8610e54c518078db77ced7530e
[color_hex] => EF9159
[avatar_url] => /assets/add_image.png
[avatar_thumb_url] =>
[has_avatar] =>
[organization_name] => testorg
[is_admin] => 1
[permissions] => Array
(
[show_company_setup] => 1
[can_see_home_data] => 1
[show_reporting] => 1
)
[is_super_pro] =>
[is_archived] =>
[impersonated] =>
)
)
[url] => /pros
)
Im basically trying to match the value that I have set in my pro_id variable
pro_0fcb8e8610e54c518078db77ced7530e
To the 'ID' Key in the array above and get the 'email' value associated to that same array and store for use later in my code.
Here is what I have so far, but no joy
foreach ($proObject as $key => $value) {
if ($key['id'] == $pro_id)
$techmail = $key['email'];
}
From my understanding of your question, and if you want to get only one element, you should be able to use array_search with array_column to get the index of the searched element. Using that you can then access the element and its corresponding email value. If you might expect more than one element I would use array_filter.
One Element:
In short:
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
) ,
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
) ,
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
$i = array_search($pro_id, array_column($proObject, 'id'));
$element = ($i !== false ? $proObject[$i] : null);
print_r($element["email"]);
?>
Multiple Elements:
In short:
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
Full code:
<?php
$proObject = array(
array(
"object" => "pro",
"id" => "pro_77c9c6a85d814e059a6a2690989bae29",
"first_name" => "Jane",
"last_name" => "Doe",
"full_name" => "Jane Doe",
"initials" => "JD",
"email" => "admin#testorg.com",
"mobile_number" => "9998761234",
"messaging_uuid" => "4547c231c3e7d0ff1796f47b88f166d5",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
),
array(
"object" => "pro",
"id" => "pro_0fcb8e8610e54c518078db77ced7530e",
"first_name" => "Robert",
"last_name" => "Jordan",
"full_name" => "Robert Jordan",
"initials" => "RJ",
"email" => "rj#testorg.com",
"mobile_number" => "4547457742",
"messaging_uuid" => "0fcb8e8610e54c518078db77ced7530e",
"color_hex" => "EF9159",
"avatar_url" => "/assets/add_image.png",
"avatar_thumb_url" => "",
"has_avatar" => "",
"organization_name" => "testorg",
"is_admin" => "1",
"permissions" => array
(
"show_company_setup" => "1",
"can_see_home_data" => "1",
"show_reporting" => "1",
),
"is_super_pro" => "",
"is_archived" => "",
"impersonated" => "",
)
);
$pro_id = "pro_0fcb8e8610e54c518078db77ced7530e";
class idEqualsFilter {
private $id;
public function __construct($id) {
$this->id = $id;
}
function __invoke($i) {
return $this->id === $i["id"];
}
};
$elements = array_filter($proObject, new idEqualsFilter($pro_id));
print_r(array_column($elements, "email"));
?>
I have a 2D array that its first dimension is an index array and the second one is an associative array.
In the array, there are some duplicates fields that I want to merge them, and for the other unduplicated fields, I want to make a third dimension array and push them there.
This is my code and array:
The entire code works correctly just the "datacontractor" field that is my third dimension does not work well.
<?php
$array=Array
(
"0" => Array
(
"sid" => 10,
"contractorid" => 1,
"fname" => "hi",
"lname" => "fam",
"sname" => "saba",
"materialname" => "beton",
"netweight" => 100,
),
"1" => Array
(
"sid" => 16,
"contractorid" => 2,
"fname" => "a",
"lname" => "a",
"sname" => "khoram",
"materialname" => "kk",
"netweight" => 200,
),
"2" => Array
(
"sid" => 16,
"contractorid" => 7,
"fname" => "a",
"lname" => "a",
"sname" => "khoram",
"materialname" => "kk",
"netweight" => 777,
),
"3" => Array
(
"sid" => 10,
"contractorid" => 5,
"fname" => "hi",
"lname" => "fam",
"sname" => "saba",
"materialname" => "beton",
"netweight" => 200,
),
"4" => Array
(
"sid" => 10,
"contractorid" => 8,
"fname" => "hi",
"lname" => "fam",
"sname" => "saba",
"materialname" => "beton",
"netweight" => 600,
),
"5" => Array
(
"sid" => 15,
"contractorid" => 9,
"fname" => "hi",
"lname" => "fam",
"sname" => "saba",
"materialname" => "beton",
"netweight" => 400,
),
);
$finalarray[]= array();
$sidlist= array();
$arraycount=count($array);
for($i=0;$i<$arraycount ;$i++) {
array_push($sidlist,$array[$i]["sid"]);
}
$sidlist = array_unique($sidlist);
$sidlistcount=count($sidlist);
$sidlist1=array();
foreach ($sidlist as $m){
array_push($sidlist1,$m);
}
for ($i = 0;$i<$sidlistcount ; $i++){
$id=$sidlist1[$i];
$datacontractor[$id]= array();
for ($j = 0;$j<$arraycount ; $j++){
if ($id==$array[$j]["sid"]){
$contractorid = $array[$j]["contractorid"];
$netweight = $array[$j]["netweight"];
$finalarray[$i]=array(
"sid" => $id,
"fname" => $array[$j]["fname"],
"lname" => $array[$j]["lname"],
"sname" => $array[$j]["sname"],
"materialname" => $array[$j]["materialname"],
"datacontractor" => $datacontractor[$id],
);
$datacontractor[$id]["$contractorid"]=$netweight;
echo $id,"<br>";
}
}
}
echo '<pre>';
print_r($finalarray);
echo '<pre>';
This is my output of this code:
but it has wrong answer in "datacontractor" field.
Array ([0] => Array
(
[sid] => 10
[fname] => hi
[lname] => fam
[sname] => saba
[materialname] => beton
[datacontractor] => Array
(
[1] => 100
[5] => 200
)
)[1] => Array
(
[sid] => 16
[fname] => a
[lname] => a
[sname] => khoram
[materialname] => kk
[datacontractor] => Array
(
[2] => 200
)
)[2] => Array
(
[sid] => 15
[fname] => hi
[lname] => fam
[sname] => saba
[materialname] => beton
[datacontractor] => Array
(
)
))
And Finally My desired output is:
Please check and tell me what my fault is.
Array ([0] => Array
(
[sid] => 10
[fname] => hi
[lname] => fam
[sname] => saba
[materialname] => beton
[datacontractor] => Array
(
[1] => 100
[5] => 200
[8] => 600
)
)[1] => Array
(
[sid] => 16
[fname] => a
[lname] => a
[sname] => khoram
[materialname] => kk
[datacontractor] => Array
(
[2] => 200
[7] => 777
)
)[2] => Array
(
[sid] => 15
[fname] => hi
[lname] => fam
[sname] => saba
[materialname] => beton
[datacontractor] => Array
(
[9] => 400
)
))
You set the "datacontractor" => $datacontractor[$id] to finalarray before finish insert all the data to the $datacontractor[$id] -> do that in separate loop.
You code is much more complicated then you actually need.
Consider the following short version:
$array = []; // this is just some of the fields - you can add all of then here
$array[] = array("id"=> 10, "contractorid" => 1,"netweight" => 100);
$array[] = array("id"=> 16, "contractorid" => 2,"netweight" => 200);
$array[] = array("id"=> 16, "contractorid" => 7,"netweight" => 777);
$array[] = array("id"=> 10, "contractorid" => 5,"netweight" => 200);
$array[] = array("id"=> 10, "contractorid" => 8,"netweight" => 600);
$array[] = array("id"=> 15, "contractorid" => 9,"netweight" => 400);
$ans = [];
foreach($array as $e) {
if (!isset($ans[$e['id']])) { // if never set do first time
$ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => $e["netweight"])); // here you can add all your other fields as fname, lname...
} else {
$ans[$e['id']]["datacontractor"][$e["contractorid"]] = $e["netweight"]; // just add the new field as already set
}
}
Now, $ans will output your desire
Edit:
For having multi contractorid value change to this:
foreach($array as $e) {
if (!isset($ans[$e['id']])) { // if never set do first time
$ans[$e['id']] = array("sid" => $e['id'], "datacontractor" => array($e["contractorid"] => [$e["netweight"]])); // notice "contractorid" has array inside (extra "[]" around $e["netweight"])
} else {
$ans[$e['id']]["datacontractor"][$e["contractorid"]][] = $e["netweight"]; // append to the contractorid array
}
}
For re-index $ans do this at the end: $ans = array_values($ans);
You can use array_reduce
$data = array_reduce($array, function ($old, $new) {
if (isset($old[$new['sid']])) {
$new['datacontractor'] = array_merge($old[$new['sid']]['datacontractor'], [$new['netweight']]);
$old[$new['sid']] = $new;
} else {
$new['datacontractor'] = [$new['netweight']];
}
unset($new['netweight']);
$old[$new['sid']] = $new;
return $old;
}, []);
$data = array_values($data);
print '<pre>';
print_r($data);
print '</pre>';
I have associative array like -
[0] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] => Austin
[address] => Phone
)
[1] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] =>
[address] => Phone
)
[3] => Array
(
[date] => 2018-06-22
[id] => 2282991
[type] => VIDEO
[domain] =>
[code] => Austin
[address] => Phone
)
I need to check is there any column having all the values are blank.
That means it should return only domain from above array because it is blank everywhere.
Is there any way to do this with minimum use of forloop? I need to check this for all these columns.
This will work if your subarray having same number of keys.Like "Date, id, Type etc".
$array = [
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "Austin", "address" => "Phone"],
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "", "address" => "Phone"],
[ "date" => "2018-06-22", "id" => 2282991, "type" => "VIDEO", "domain" =>'', "code" => "Austin", "address" => "Phone"]
];
$empty = [];
foreach($array[0] as $key=>$val){
$error = array_column($array, $key);
if(empty (array_filter($error)) ) {
$empty[] = $key;
}
}
print_r($empty);
Output:
Array
(
[0] => domain
)
This is my array,
array
(
[0] => Array
(
[Invoice_id] => 1
[Customer_Name] => Abcd Ltd
[Order_Created] => 2018-02-07
[Order_Delivery_Date] => 2018-02-17
[State_Code] => 35
[CGST] => 212.5
[SGST] => 212.5
[IGST] => 0
[Total_Amount] => 8925
)
[1] => Array
(
[Invoice_id] => 2
[Customer_Name] => Johnson and Sons
[Order_Created] => 2018-02-07
[Order_Delivery_Date] => 2018-02-17
[State_Code] => 35
[CGST] => 2975
[SGST] => 2975
[IGST] => 0
[Total_Amount] => 124950
)
)
How to convert this array like below,
array
(
array("invoice_id" => "1", "customer_name" => "Abcd Ltd", "order_created" => 2018-02-07, "delivery_date" => 2018-02-17, "state_code" => 35, "cgst" =>212.5, "sgst" =>212.5, "igst" =>0, "total_amount" =>8925),
array("invoice_id" => "2", "customer_name" => "Johnson and Sons", "order_created" => 2018-02-07, "delivery_date" => 2018-02-17, "state_code" => 35, "cgst" =>2975, "sgst" =>2975, "igst" =>512.5, "total_amount" =>124950)
);
You already have it in the format you want, they are just in different ways of displaying arrays, except that your arrays are indexed by keys, if you really want to unindex it use this $newArray = array_values($array)
You could try this to change keys of your array :
foreach ($array as $k => $item) {
foreach ($item as $key => $value) {
unset($array[$k][$key]) ; // remove old key
$array[$k][strtolower($key)] = $value ; // add new one
}
}
Then "Invoice_id" keys will be "invoice_id", and so on.
I want to update the user table from request table using laravel 5
Please suggest how it can be done with ease. I have two tables data and want to update user table based on request table data where request table has foreign sm_id and user table has primary id please suggest
Thanks in advance
Request data:
Array (
[0] => Array ( [id] => 1 [sm_id] => 1 [field_name] => first_name [value] => G2 [created_at] => 2017-02-27 14:17:35 [updated_at] => 2017-02-24 11:05:03 [deleted_at] => )
[1] => Array ( [id] => 2 [sm_id] => 4 [field_name] => phone [value] => 123467890 [created_at] => 2017-02-27 16:55:48 [updated_at] => 2017-02-27 11:02:27 [deleted_at] => )
[2] => Array ( [id] => 3 [sm_id] => 4 [field_name] => first_name [value] => John [created_at] => 2017-02-27 16:55:48 [updated_at] => 2017-02-27 11:02:27 [deleted_at] => )
[3] => Array ( [id] => 4 [sm_id] => 4 [field_name] => last_name [value] => Hunny [created_at] => 2017-02-27 16:55:48 [updated_at] => 2017-02-27 11:02:27 [deleted_at] => ) )
User Data:
Array
(
[id] => 4
[social_id] =>
[role_id] => 0
[name] =>
[first_name] => max
[last_name] => rony
[gender] => male
[dob] => 02-02-2017
[language] => english
[location] => USA
[address] => ABCD
[email] => max.jrny#jioc.com
[phone] => 7894561230
[id_proof] =>
[id_proof_path] =>
[remember_token] =>
[provider] => website
[biography] => Here is about
[approve] => 1
[created_at] => 2017-02-22 12:16:56
[updated_at] => 2017-02-22 12:16:56
[deleted_at] =>
)
Expected result in user table
Array
(
[id] => 4
[social_id] =>
[role_id] => 0
[name] =>
[first_name] => john
[last_name] => Hunny
[gender] => male
[dob] => 02-02-2017
[language] => english
[location] => USA
[address] => ABCD
[email] => max.jrny#jioc.com
[phone] => 123467890
[id_proof] =>
[id_proof_path] =>
[remember_token] =>
[provider] => website
[biography] => Here is about
[approve] => 1
[created_at] => 2017-02-22 12:16:56
[updated_at] => 2017-02-22 12:16:56
[deleted_at] =>
)
Here is my code
public function verifyInformation($id){
if($id){
$getRequest = request::all()->toArray();
$user = User::where('id', $id)->first()->toArray();
foreach($getRequest as $row=>$value){
foreach($value as $rowKey => $result){
$array_key = array_keys($user);
$arrayDiff = array_diff($value, $user);
$find = $arrayDiff['field_name'];
if(in_array($find, $array_key)){
foreach($array_key as $k => $v){
if($v == $find){
$fieldKey = $v;
$fieldValue = $arrayDiff['value'];
if($fieldValue){
$user = new User;
$user->$fieldKey = $fieldValue;
$user->save();
return redirect()->back()->with("status", "Well done!! profile updated successfully");
}
}
}
}
}
}
}
}
Note: only phone, first_name and last_name updated in expected result
This code will provide an updated array to save and indicate if any values have changed. It is just four declarations to set things up, followed by a foreach loop containing a condition statement which commands the push of data into the array. Modify my snippet to suit your purpose.
Demo
$request_data=array(
0=>array(
"id" => 1,
"sm_id" => 1,
"field_name" => "first_name",
"value" => "G2",
"created_at" => "2017-02-27 14:17:35",
"updated_at" => "2017-02-24 11:05:03",
"deleted_at" => ""),
1=>array(
"id" => 2,
"sm_id" => 4,
"field_name" => "phone",
"value" => 123467890,
"created_at" => "2017-02-27 16:55:48",
"updated_at" => "2017-02-27 11:02:27",
"deleted_at" => ""
),
2=>array(
"id" => 3,
"sm_id" => 4,
"field_name" => "first_name",
"value" => "John",
"created_at" => "2017-02-27 16:55:48",
"updated_at" => "2017-02-27 11:02:27",
"deleted_at" => ""
),
3=>array(
"id" => 4,
"sm_id" => 4,
"field_name" => "last_name",
"value" => "Hunny",
"created_at" => "2017-02-27 16:55:48",
"updated_at" => "2017-02-27 11:02:27",
"deleted_at" => ""
)
);
$user_data=array(
"id" => 4,
"social_id" => "",
"role_id" => 0,
"name" => "",
"first_name" => "max",
"last_name" => "rony",
"gender" => "male",
"dob" => "02-02-2017",
"language" => "english",
"location" => "USA",
"address" => "ABCD",
"email" => "max.jrny#jioc.com",
"phone" => "7894561230",
"id_proof" => "",
"id_proof_path" => "",
"remember_token" => "",
"provider" => "website",
"biography" => "Here is about",
"approve" => 1,
"created_at" => "2017-02-22 12:16:56",
"updated_at" => "2017-02-22 12:16:56",
"deleted_at" => ""
);
$new_data=$user_data;
$user_id=$user_data["id"]; // declare target id
$request_ids=array_column($request_data,"sm_id"); // read sm_id column to array
$request_indexes=array_keys($request_ids,$user_id); // declare matching indexes
// loop an subarrays that contain the appropriate sm_id
foreach(array_intersect_key($request_data,array_flip($request_indexes)) as $row){
// if row contains one of the chosen values, overwrite the original data
if(in_array($row["field_name"],array("phone","first_name","last_name"))){
$new_data[$row["field_name"]]=$row["value"];
}
}
if($user_data!=$new_data){
echo "Changes to save";
}else{
echo "No changes to save";
}
echo "<pre>";
var_export($new_data);
echo "</pre>";
This is the output:
Changes to save
array (
'id' => 4,
'social_id' => '',
'role_id' => 0,
'name' => '',
'first_name' => 'John',
'last_name' => 'Hunny',
'gender' => 'male',
'dob' => '02-02-2017',
'language' => 'english',
'location' => 'USA',
'address' => 'ABCD',
'email' => 'max.jrny#jioc.com',
'phone' => 123467890,
'id_proof' => '',
'id_proof_path' => '',
'remember_token' => '',
'provider' => 'website',
'biography' => 'Here is about',
'approve' => 1,
'created_at' => '2017-02-22 12:16:56',
'updated_at' => '2017-02-22 12:16:56',
'deleted_at' => '',
)