DRY array in php - php

Hello I am trying to apply the DRY concept to my program which now has over 3000 lines of codes just because i have been repeating myself a lot.
I have this array:
// prepare the sales payload
$sales_payload = array(
'organization_id' => $getOrg['data'][0]['id'],
'contact_id' => $contact_id,
'status' => 'Open',
'responsible_employee_id' => 'employee:50c76c15262b12d36d44e34a3f0f8c3d',
'source' => array(
'id' => $source['data'][0]['id'],
'name' => $source['data'][0]['name'],
),
'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - "."Online marketing Duitsland",
'start_date' => date("Y-m-d"), // set start date on today
'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now
'chance_to_score' => '10%',
'expected_revenue' => 0, //set the expected revenue
'note' => $_POST['order_comments'],
'progress' => array(
'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress
),
"custom_fields" => [["voorstel_diensten"=>implode("-",$online_marketing_check)]],
);
Is there a way I can dynamically change certain fields only instead of copying the whole thing and manually changing it.

You can declare a function that clones the array and changes it
function arrayClone($args){
$sales_payload = array(
'organization_id' => $getOrg['data'][0]['id'],
'contact_id' => $contact_id,
'status' => 'Open',
'responsible_employee_id' => 'employee:50c76c15262b12d36d44e34a3f0f8c3d',
'source' => array(
'id' => $source['data'][0]['id'],
'name' => $source['data'][0]['name'],
),
'subject' => " ".str_replace($strToRemove, "", $_POST['billing_myfield12'])." - "."Online marketing Duitsland",
'start_date' => date("Y-m-d"), // set start date on today
'expected_closing_date' => date("Y-m-d",strtotime(date("Y-m-d")."+ 14 days")), // set expected closing date 2 weeks from now
'chance_to_score' => '10%',
'expected_revenue' => 0, //set the expected revenue
'note' => $_POST['order_comments'],
'progress' => array(
'id'=>'salesprogress:200a53bf6d2bbbfe' //fill a valid salesprogress id to set proper sales progress
),
"custom_fields" => [["voorstel_diensten"=>implode("-",$online_marketing_check)]],
);
return array_replace_recursive($sales_payload, $args);
}
How tu use it:
$a = arrayClone(['status' => 'Closed', 'contact_id' => 5]);
$b = arrayClone(['status' => 'Closed Now', 'contact_id' => 20]);

Related

Parse json string which is broken due to unicode characters and slashes

I'm trying to received data from Android to Laravel using API. Below are the data that I received in format object array list.
$obj = '{ "registerDetails": "{"accountName":"hh h hc","accountNumber":"868686","addressUser":"cg h jc","bankId":1,"selectedCityId":1,"emergencyName":"g g h","emergencyNumber":"0686868","education":[{"certificatePicture":{"body":{},"headers":{"namesAndValues":["Content-Disposition","form-data; name\u003d\"certificateFile\"; filename\u003d\"2022-11-30-00-56-28-598.jpeg\""]}},"grade":"hxycucu","educationLvl":"STPM / A Level or Equivalent","endEducation":"Dec 2022","id":4,"institutionName":"yxyxyxy","isEducationExpandable":false,"startEducation":"Nov 2022"}],"skill":[{"id":8},{"id":10}],"work":[{"companyName":"cuvuv","jobEndDate":"Nov 2022","isCurrentlyWorkHere":true,"isJobExpand":true,"jobPosition":"g cuc","jobScope":"cuccu","jobTitle":"6ff7f","jobStartDate":"Oct 2022"}],"phoneUser":"906886","postCode":"058686","selectedStateId":1}", "myKadFile": {}, "selfieFile": {} }';
I already attempted to decode the object, but it returned NULL.
Here's what I tried:
var_dump(json_decode($obj, true));
Bruteforce trial and error json repair at its finest:
The problem stems from those pesky unicode = (\u003d) characters.
I needed to replace them and handle slashes.
...In case I need to clarify for anyone...
THIS IS A HACK!!!!
Code: (Demo)
$fixed = preg_replace('/\\\\u003d\\\\\\\\(.*?)\\\\\\\\/', '=\\\\\\\\\\\\$1\\\\\\\\\\\\', $obj);
var_export(
json_decode(json_decode($fixed)->registerDetails)
);
Output:
(object) array(
'accountName' => 'gsyau',
'accountNumber' => '168454',
'addressUser' => 'test',
'bankId' => 1,
'selectedCityId' => 1,
'emergencyName' => 'test',
'emergencyNumber' => '0146542346',
'education' =>
array (
0 =>
(object) array(
'certificatePicture' =>
(object) array(
'body' =>
(object) array(
),
'headers' =>
(object) array(
'namesAndValues' =>
array (
0 => 'Content-Disposition',
1 => 'form-data; name="certificateFile"; filename="2022-11-29-21-18-35-294.jpg"',
),
),
),
'grade' => 'test',
'educationLvl' => 'Doctoral (PHD) or Equivalent',
'endEducation' => 'Oct 2022',
'id' => 8,
'institutionName' => 'test',
'isEducationExpandable' => false,
'startEducation' => 'Aug 2022',
),
),
'skill' =>
array (
0 =>
(object) array(
'id' => 7,
),
1 =>
(object) array(
'id' => 9,
),
),
'work' =>
array (
0 =>
(object) array(
'companyName' => 'test',
'jobEndDate' => 'Oct 2022',
'isCurrentlyWorkHere' => false,
'isJobExpand' => false,
'jobPosition' => 'testtest',
'jobScope' => 'test',
'jobTitle' => 'test',
'jobStartDate' => 'Aug 2022',
),
),
'phoneUser' => '014654264',
'postCode' => '68100',
'selectedStateId' => 1,
)

Looping an array within an array php

Hi there i need some help to loop an array of items.
The part that I have repeated needs to be looped in order to get multiple items from the database. At this stage I am only to invoice one item where as users generally purchase a few so i need to run a foreach statement I think. Please excuse my ignorance and lack of understanding, I have tried a series of things but they do not seem to work
$json1 = array(
'Date' => $currentDate->format('Y-m-d\TH:i:s'),
'Customer' => array(
'DisplayID' => $phone
),
'CustomerPurchaseOrderNumber' => $ordID,
'Freight' => '0',
'BalanceDueAmount' => '0.0',
'Status' => 'Closed',
'Lines' => /*$orderDetails,*/ array(
array(
'ShipQuantity' => $ShowDetails['quantity'],
'UnitPrice' => $ShowDetails['unit_price'],
'Total' => $ShowDetails['total_price'],
'Item' => array(
'UID' => $productUID,//itemuid(609400gmkit)
),
'Description' => $productTitle. ' ' .$sizeTitle. ' '
.$colorTitle,
'TaxCode' => array(
'UID' => '7d1f2e99-ffe0-4463-9c29-
61d078b392d3'//taxcodeuid(GST)
)
)
),
'Freight' => $shippingprice,//if dg then $10 otherwise $0 unless below
$100
'ShippingMethod' => $ShippingMethod,// if dg the 'MyFreight' otherwise
'transdirect'
);
The portion that i need to loop is as follows :
array(
'ShipQuantity' => $ShowDetails['quantity'],
'UnitPrice' => $ShowDetails['unit_price'],
'Total' => $ShowDetails['total_price'],
'Item' => array(
'UID' => '27d56af8-d3d6-4f0a-b71b-
4586fffbd63a'//itemuid(609400gmkit)
),
'Description' => $productTitle. ' ' .$sizeTitle. ' '
.$colorTitle,
'TaxCode' => array(
'UID' => '7d1f2e99-ffe0-4463-9c29-
61d078b392d3'//taxcodeuid(GST)
)
)*/

Auth.net eCheck implementation using John Conde's AuthnetXML Class

I have an existing implementation of this class processing subscriptions by credit card but I now need to add the facility to accept payment by eCheck but I am unsure of how to change this portion of the code:
'payment' => array(
'creditCard' => array(
'cardNumber' => '4111111111111111',
'expirationDate' => '2016-08'
)
),
I have come up with the following from referencing the AIM guide pdf and AIM guide XML pdf
'payment' => array(
'bankAccount' => array( // x_method equivalent ?
'routingNumber' => '', // x_bank_aba_code equivalent ?
'accountNumber' => '', // x_bank_acct_num equivalent ?
'nameOnAccount' => '', // x_bank_acct_name equivalent ?
'bankName' => '', // x_bank_name equivalent ?
'echeckType' => 'WEB' // x_echeck_type equivalent
/*
x_bank_acct_type has no equivalent ?
*/
)
),
but there appears to be some discrepancies between the required fields?
Any pointers before I start on this would be greatly appreciated.
Looking at Authorize.Net's documentation this should work:
'payment' => array(
'bankAccount' => array(
'accountType' => '', // 'checking'
'routingNumber' => '',
'accountNumber' => '',
'nameOnAccount' => ''
)
),
Following on from John's answer this is the complete code I used to solve this for anyone finding this through a google search:
$xml->ARBCreateSubscriptionRequest(array(
'subscription' => array(
'name' => 'SubscriptionName',
'paymentSchedule' => array(
'interval' => array(
'length' => '1',
'unit' => 'months'
),
'startDate' => date('Y-m-d', time()), // Format: YYYY-MM-DD
'totalOccurrences' => '9999' // To submit a subscription with no end date (an ongoing subscription), this field must be submitted with a value of 9999
),
'amount' => $eCart1->GrandTotal(), // total monthly subscription
'payment' => array(
'bankAccount' => array(
'accountType' => ((isset($_POST["accountType"]))?$_POST["accountType"]:""), // options available are checking or businessChecking in this instance
'routingNumber' => ((isset($_POST["routingNumber"]))?$_POST["routingNumber"]:""),
'accountNumber' => ((isset($_POST["accountNumber"]))?$_POST["accountNumber"]:""),
'nameOnAccount' => ((isset($_POST["nameOnAccount"]))?$_POST["nameOnAccount"]:""),
'echeckType' => ((isset($_POST["echeckType"]))?$_POST["echeckType"]:"") // if businessChecking is chosen then 'CCD' else 'WEB'
)
),
'customer' => array(
'id' => "'".$_SESSION['clientID']."'",
'email' => "'".((isset($_POST["email"]))?$_POST["email"]:"")."'"
),
'billTo' => array(
'firstName' => "'".((isset($_POST["firstname"]))?$_POST["firstname"]:"")."'",
'lastName' => "'".((isset($_POST["lastname"]))?$_POST["lastname"]:"")."'",
'company' => "'".((isset($_POST["company"]))?$_POST["company"]:"")."'",
'address' => "'".((isset($_POST["street1"]))?$_POST["street1"]:"")."'",
'city' => "'".((isset($_POST["city"]))?$_POST["city"]:"")."'",
'state' => "'".((isset($_POST["state_province"]))?$_POST["state_province"]:"")."'",
'zip' => "'".((isset($_POST["postcode"]))?$_POST["postcode"]:"")."'"
)
)
));

rewrite php array based on condition

I have one array and i want change the vehicle price based on number of days here is my array want to rewrite the array,i get number of days i get $rental_days and based on that total price is multiplied,now i want to change it such that if days are 1,2,3,4 than charge will be applied if 5,6,7 than the last price will be applicable then how should i rewrite an array based on this condition (total_price)?
$vehicles[$result['vehicle_id']] = array(
'vehicle_id' => $result['vehicle_id'],
'title' => $result['manufacturer']." ".$result['series'],
'manufacturer' => $result['manufacturer'],
'series' => $result['series'],
'year' => $result['year'],
'class' => $result['class'],
'image' => $image,
'image_thumb' => $image_thumb,
'description' => $description,
'seats' => $vehicle_meta['seats'],
'doors' => $vehicle_meta['doors'],
'conditioning' => $vehicle_meta['conditioning'],
'transmission' => $vehicle_meta['transmission'],
'total_price' => $rc_currency->format($rental_days*$result['rent']),
'daily_price' => $rc_currency->format($result['rent'])
);
If I understand you correctly....
Do your if statement to check for days, then apply the charge to the total at the bottom
Not sure if you want to apply the charge once, or times it by the amount of days as well...I'll leave that to you to figure out
if(($rental_days>0)&&($rental_days<=4)){
$charge = 12.00; //whatever you charge for 4 days
} elseif(($rental_days>4)&&($rental_days<=7)){
$charge = 25.00; //whatever you charge for 567 days
} elseif($rental_days>7){
$charge = 40.00; //whatever you charge for 8 days
} else {$charge = 0;}
$vehicles[$result['vehicle_id']] = array(
'vehicle_id' => $result['vehicle_id'],
'title' => $result['manufacturer']." ".$result['series'],
'manufacturer' => $result['manufacturer'],
'series' => $result['series'],
'year' => $result['year'],
'class' => $result['class'],
'image' => $image,
'image_thumb' => $image_thumb,
'description' => $description,
'seats' => $vehicle_meta['seats'],
'doors' => $vehicle_meta['doors'],
'conditioning' => $vehicle_meta['conditioning'],
'transmission' => $vehicle_meta['transmission'],
'total_price' => $rc_currency->format(($rental_days*$result['rent'])+$charge),
'daily_price' => $rc_currency->format($result['rent'])
);

MongoDB aggregate with PHP - group by on date

I am using an aggregate in MongoDB with PHP. The code looks like:
$results = $c->aggregate(array(
array(
'$project' => array(
'day' => array('$dayOfYear' => '$executed')
),
),
array(
'$group' => array(
'_id' => array('day' => '$day'),
'count' => array('$sum' => 1)
),
),
array(
'$sort' => array(
'_id' => 1
),
),
array(
'$limit' => 30
)
));
The problem with this, is that $dayOfYear does not sort correctly, because it sorts 2 then 3 then 345, 346... I need it to be date ascending. So, basically instead of simply doing $dayOfYear I need something like $year-$month-$dayOfMonth.
Unfortunately this does not work. Any ideas?
Thanks.
You can project those parts out and then group on them to enable you to group on the whole date:
$results = $c->aggregate(array(
array(
'$project' => array(
'year' => array('$year' => '$executed' ),
'month' => array('$month' => '$executed' ),
'day' => array('$dayOfMonth' => '$executed')
),
),
array(
'$group' => array(
'_id' => array('year' => '$year', 'month' => '$month', 'day' => '$day'),
'count' => array('$sum' => 1)
),
),
array(
'$sort' => array(
'_id.year' => 1,
'_id.month' => 1,
'_id.day' => 1
),
),
array(
'$limit' => 30
)
));
Something like that should do the trick allowing you to sort on, as you stated: $year-$month-$dayOfMonth.
You shouldn't sort on the entire _id because you've set that up to contain an object (which can sort oddly), so change your $sort to this instead to specifically sort by day of year:
'$sort' => array(
'_id.day' => 1
),

Categories