parse data from JSON callback using PHP - php

I receive a callback data from payment site and try to save some values into txt file
Getting an array:
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
Saving all data to txt:
file_put_contents('robot.php', var_export($obj, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);
The result from txt:
array (
'rrn' => '',
'masked_card' => '444455XXXXXX1111',
'sender_cell_phone' => '',
'response_status' => 'success',
'sender_account' => '',
'fee' => '',
'rectoken_lifetime' => '',
'reversal_amount' => '0',
'settlement_amount' => '0',
'actual_amount' => '370000',
'order_status' => 'approved',
'response_description' => '',
'verification_status' => '',
'order_time' => '04.01.2018 21:53:47',
'actual_currency' => 'JPY',
'order_id' => 1515095627',
'parent_order_id' => '',
'merchant_data' => '[{"name":"custom-field-0","label":"fist_name","value":"john_doe"},{"name":"custom-field-2","label":"phone","value":"07777777777"}]',
'tran_type' => 'purchase',
'eci' => '5',
'settlement_date' => '',
'payment_system' => 'card',
'rectoken' => '',
'approval_code' => '56783909',
'merchant_id' => 14066776208,
'settlement_currency' => '',
'payment_id' => 7487818gg3,
'product_id' => '',
'amount' => '370000',
'sender_email' => 'admin#none.in.ua',
)
How to save in txt separate values from nested array 'merchant_data' - first name and phone?

You can make new array and save it to file:
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$save = [];
foreach ($obj['merchant_data'] as $data){
$save[] = [
'name' => $data['first_name'],
'phone' => $data['phone'],
];
}
file_put_contents('robot.php', var_export($save, true) . "\r\n\r\n", FILE_APPEND | LOCK_EX);

Related

How to remove extra array in arrays list in laravel

Screenshot
As you see my data are loaded inside extra SNHISTORY array and I need to remove that extra array.
Code
Lines regarding to screenshot results are commented.
$array = [];
foreach($internalTransits as $key => $item) {
foreach($item->barcodes as $barcode){}
$a = $item->barcodes;
$grouped = $a->mapToGroups(function ($item, $key) {
return [
'SNHISTORY' => [ // my arrays to move out
'_attributes' => [
'operation' => 'Ret'
],
'SERIALNUMBER' => $item['serial_number'] ? $item['serial_number'] : $item['u_serial_number'],
'EXPIREDDATE' => $item['created_at']->format('Y-m-d'),
'QUANTITY' => '1',
'SNSIGN' => '-1',
],
'ITEMUNIT' => $item['product']['unit'],
'UNITPRICE' => $item['product']['price'],
];
});
$year = Carbon::createFromFormat('Y-m-d H:i:s', $item['created_at'])->year;
$month = Carbon::createFromFormat('Y-m-d H:i:s', $item['created_at'])->month;
$timeline[$key][] = [
'_attributes' => [
'operation' => 'Add'
],
'KeyID' => $barcode['product']['id'],
'ITEMNO' => $barcode['product']['sku'],
'QUANTITY' => '1',
'ITEMUNIT' => $barcode['product']['unit'],
'UNITRATIO' => '1',
'ITEMRESERVED1' => '',
'ITEMRESERVED2' => '',
'ITEMRESERVED3' => '',
'ITEMRESERVED4' => '',
'ITEMRESERVED5' => '',
'ITEMRESERVED6' => '',
'ITEMRESERVED7' => '',
'ITEMRESERVED8' => '',
'ITEMRESERVED9' => '',
'ITEMRESERVED10' => '',
'UNITPRICE' => $barcode['product']['price'],
'QTYCONTROL' => '0',
'SNHISTORY' => $grouped->toArray(), // this has extra array where my actual arrays are loaded inside of it
];
$array['TRANSACTIONS'] = [
'_attributes' => [
'OnError' => 'CONTINUE'
],
];
$array['TRANSACTIONS']['WTRAN'] = [
'_attributes' => [
'operation' => 'Add',
'REQUESTID' => '1',
],
'TRANSFERID' => $item['id'],
'TRANSACTIONID' => '',
'TRANSFERNO' => $item['transNu'],
'TRANSFERDATE' => $item['created_at']->format('Y-m-d'),
'DESCRIPTION' => $item['description'],
'FROMWHID' => $barcode['outlet'][0]['name'],
'TOWHID' => $item->toOutlet->name,
'FROMWHADDRESS' => '',
'TOWHADDRESS' => '',
];
$array['TRANSACTIONS']['WTRAN']['ITEMLINE'] = $timeline;
}
What I've tried
I cannot change 'SNHISTORY' => $grouped->toArray(), to something like $grouped->toArray(), under $timeline[$key][] = [ it will return error
I cannot add $array['TRANSACTIONS']['WTRAN']['ITEMLINE']['SNHISTORY'] = $grouped->toArray(); and remove 'SNHISTORY' => $grouped->toArray(), it will return error known bug
Question
How can I remove extra SNHISTORY around my data?
As mentioned in the comments section, you probably want to merge both arrays together:
$timeline[$key][] = [
'_attributes' => [
'operation' => 'Add'
],
'KeyID' => $barcode['product']['id'],
'ITEMNO' => $barcode['product']['sku'],
'QUANTITY' => '1',
'ITEMUNIT' => $barcode['product']['unit'],
'UNITRATIO' => '1',
'ITEMRESERVED1' => '',
'ITEMRESERVED2' => '',
'ITEMRESERVED3' => '',
'ITEMRESERVED4' => '',
'ITEMRESERVED5' => '',
'ITEMRESERVED6' => '',
'ITEMRESERVED7' => '',
'ITEMRESERVED8' => '',
'ITEMRESERVED9' => '',
'ITEMRESERVED10' => '',
'UNITPRICE' => $barcode['product']['price'],
'QTYCONTROL' => '0',
] + $grouped->toArray();
as i can see in your screen shot data
you are getting xml data you need to convert that into array
function xmlToArray($xml_string)
{
$doc = #simplexml_load_string($xml_string);
if ($doc) {
$xml = simplexml_load_string($xml_string);
$json = json_encode($xml);
return json_decode($json, true);
}
}
then u will get real array then u don't need to remove that as that is a parent key

mongo php library updateOne & insertOne damaging collection

I have an application I am trying to update from legacy to new driver. I am having a problem with collections being damaged when the below code is triggered. I think I have narrowed it down here.
function update($collection,$criteria,$data,$insertIfNotExists = false)
{
if(!empty($collection) && !empty($criteria) && !empty($data)) {
if (!isset($this->collection[$collection])) {
$this->collection[$collection] = (new MongoDB\Client)->hebe->{$collection};
}
if ($insertIfNotExists) {
$oldData = $this->collection[$collection]->findOne($criteria);
if ($oldData == NULL) {
$data['createdDate'] = date("Y-m-d H:i:s");
$data['modifiedDate'] = (isset($data['modifiedDate'])) ? $data['modifiedDate']:date("Y-m-d H:i:s");
/*
return ($this->collection[$collection]->insertOne($data)) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
} else {
$newData = $oldData;
foreach($data as $n=>$v) {
$newData[$n] = $v;
}
$newData['modifiedDate'] = (isset($newData['modifiedDate'])) ? $newData['modifiedDate']:date("Y-m-d H:i:s");
/*
return ($this->collection[$collection]->updateOne($criteria,['$set' => $newData])) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
}
} else {
/*
return ($this->collection[$collection]->updateOne($criteria,['$set' => $data])) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
}
}
}
example variables are
$collection = 'customer'
$criteria = array ( 'number' => '9999',)
$data = array (
'number' => '9999',
'name' => 'Testing Account',
'reference' => 'Peter Smith',
'defaultDeliveryAddress' => 1,
'visitAddress' => '',
'address' => '',
'district' => 'Marknad',
'postAddress' => '',
'orgNumber' => '5562041771',
'phone' => '031-7802700',
'fax' => '031-193328',
'groupCode' => 'int',
'creditCustomer' => '',
'typeOfDelivery' => 'Bil',
'typeOfPayment' => '10',
'emailAddresses' =>
array (
'invoice' => 'email1#domain.com',
'order' => 'email2#domain.com',
'deliveryNote' => 'email3#domain.com',
'packingSlip' => 'email4#domain.com',
),
'orderType' => NULL,
'termsOfDelivery' => 'RC',
'creditLimit' => 100000.0,
'pricelist' => 4,
'pricelist1' => '',
'pricelist2' => '9998',
'pricelist3' => '104',
'discount' => NULL,
'countryCode' => 'SE',
'currencyCode' => 'SEK',
'blocked' => 0,
'deliveryCost' => 0,
'vatCode' => '2',
'email' => 'peremail#domain.com',
'password' => 'password',
'modifiedDate' => '2019-06-25 00:00:00',
'deliveryAddresses' =>
array (
0 =>
array (
'row' => 1,
'name' => 'Test Address',
'address' => 'Box 12345',
'postAddress' => '42246',
'default' => true,
),
1 =>
array (
'number' => '9999',
'name' => 'Testing Address',
'reference' => '13232',
'address' => 'Box 12245',
'postAddress' => '42246',
),
),
'references' =>
array (
0 =>
array (
'number' => '9999',
'name' => 'Testing',
'email' => '',
'password' => '',
),
1 =>
array (
'number' => '9999',
'name' => 'Testing2',
'email' => '',
'password' => 'password',
),
2 =>
array (
'number' => '9999',
'name' => 'Peter Smith',
'email' => '',
'password' => 'password',
),
),
)
Can someone point me in the right direction on what I am doing wrong with updateOne and insertOne. From what I understand by the docs is it supports array.
EDIT: a little background is I upgraded this system and MongoDB from 2.6 to 3.6. I also upgraded mongodb driver from legacy mongo.
The problem was the old data in the collection had quotations and the updateOne/insertOne data did not. Correcting this seem to solve the problem.

phpexcel - add new row in existing excel file using phpexcel

All data in array like this
<?php
$sub_arr = array();
$sub_arr[] = array(
'sr_nm' => 1,
'recept_number' => 3019,
'adm_number' => 3434,
'student_name' => 'amit',
'class' => 'LKG',
'pay' => 'online',
'cheq_nm' => '',
'adm_fee' => '',
'consolidated' => '',
'sec.fee' => '',
'dev.charge' => 5000,
'school_fee' => 1300,
'subling' => '-3400',
'transport' => 2300,
'late_fee' =>'total' => 35006
);
$sub_arr[] = array('sr_nm' => 1,
'recept_number' => 3019,
'adm_number' => 3434,
'student_name' => 'amit',
'class' => 'LKG',
'pay' => 'online',
'cheq_nm' => '',
'adm_fee' => '',
'consolidated' => '',
'sec.fee' => '',
'dev.charge' => 5000,
'school_fee' => 1300,
'subling' => '-3400',
'transport' => 2300,
'late_fee' => '',
'total' => 35006
);
And my excel file:
I want to insert new data from A4 shell after loading the file.

PHP - Creating an array from CSV and then echo the values

I am attempting to parse CSV strings into a multi-dimensional array. I am using the following code to do this...
public function exportPartsAuthority($fileArray)
{
foreach ($fileArray as $filename => $fileContent) {
$lines = explode("\n", $fileContent);
$formatting = explode(",", $lines[0]);
unset($lines[0]);
$results = array();
foreach ( $lines as $line ) {
$parsedLine = str_getcsv( $line, ',' );
$result = array();
foreach ( $formatting as $index => $caption ) {
if(isset($parsedLine[$index])) {
$result[$formatting[$index]] = trim($parsedLine[$index]);
} else {
$result[$formatting[$index]] = '';
}
}
$results[] = $result;
}
$var_str = var_export($results, true);
$var = "<?php\n\n\$$values = $var_str;\n\n?>";
file_put_contents('/home/apndev/public_html/output.txt', $var);
}
}
The end result is this:
$ = array (
0 =>
array (
'Ordernumber' => '100000002',
'Orderdate' => '02/10/2013',
'OrderStatus' => 'pending',
'PurchasedWebsite' => 'Main Website - Main Website Store - Default Store View',
'PaymentMethod' => 'checkmo',
'ShippingMethod' => 'flatrate_flatrate',
'Subtotal' => '2.0000',
'ShippingCost' => '10.0000',
'GrandTotal' => '12.0000',
'TotalTax' => '0.0000',
'TotalPaid' => '',
'TotalRefunded' => '',
'ItemName' => 'K&N Air Filter Wrap',
'ItemSKU' => 'YA-6504PK K&N',
'ItemISBN' => '',
'ItemStock' => '',
'ItemPrice' => '1.0000',
'CostPrice' => '',
'ItemOrdered' => '1.0000',
'ItemInvoiced' => '0.0000',
'ItemSent' => '0.0000',
'CustomerID' => '1',
'BillingFirstName' => 'Brian',
'BillingLastName' => '',
'BillingCompany' => '',
'BillingE-Mail' => '',
'BillingPhone' => '',
'BillingAddress1' => '',
'BillingAddress2' => '',
'BillingCity' => '',
'BillingPostcode' => '',
'BillingState' => 'Florida',
'BillingCountry' => 'US',
'ShippingFirstName' => 'Brian',
'ShippingLastName' => '',
'ShippingCompany' => '',
'ShippingE-Mail' => '',
'ShippingPhone' => '',
'ShippingAddress1' => '',
'ShippingAddress2' => '',
'ShippingCity' => '',
'ShippingPostcode' => '',
'ShippingState' => 'Florida',
'ShippingCountry' => 'US',
'Vendor SKU' => '',
'Line Code
' => '',
),
1 =>
array (
'Ordernumber' => '100000002',
'Orderdate' => '02/10/2013',
'OrderStatus' => 'pending',
'PurchasedWebsite' => 'Main Website - Main Website Store - Default Store View',
'PaymentMethod' => 'checkmo',
'ShippingMethod' => 'flatrate_flatrate',
'Subtotal' => '2.0000',
'ShippingCost' => '10.0000',
'GrandTotal' => '12.0000',
'TotalTax' => '0.0000',
'TotalPaid' => '',
'TotalRefunded' => '',
'ItemName' => 'K&N Air Filter Wrap',
'ItemSKU' => 'YA-6601-TDK K&N',
'ItemISBN' => '',
'ItemStock' => '',
'ItemPrice' => '1.0000',
'CostPrice' => '',
'ItemOrdered' => '1.0000',
'ItemInvoiced' => '0.0000',
'ItemSent' => '0.0000',
'CustomerID' => '1',
'BillingFirstName' => 'Brian',
'BillingLastName' => '',
'BillingCompany' => '',
'BillingE-Mail' => '',
'BillingPhone' => '',
'BillingAddress1' => '',
'BillingAddress2' => '',
'BillingCity' => '',
'BillingPostcode' => '',
'BillingState' => 'Florida',
'BillingCountry' => 'US',
'ShippingFirstName' => 'Brian',
'ShippingLastName' => '',
'ShippingCompany' => '',
'ShippingE-Mail' => '',
'ShippingPhone' => '',
'ShippingAddress1' => '',
'ShippingAddress2' => '',
'ShippingCity' => '',
'ShippingPostcode' => '',
'ShippingState' => 'Florida',
'ShippingCountry' => 'US',
'Vendor SKU' => '',
'Line Code
' => '',
),
2 =>
array (
'Ordernumber' => '100000003',
'Orderdate' => '07/10/2013',
'OrderStatus' => 'pending',
'PurchasedWebsite' => 'Main Website - Main Website Store - Default Store View',
'PaymentMethod' => 'checkmo',
'ShippingMethod' => 'flatrate_flatrate',
'Subtotal' => '1716.5000',
'ShippingCost' => '5.0000',
'GrandTotal' => '1721.5000',
'TotalTax' => '0.0000',
'TotalPaid' => '',
'TotalRefunded' => '',
'ItemName' => 'Cardone High Pressure Diesel Injection Oil Pump',
'ItemSKU' => '2P-225 Cardone',
'ItemISBN' => '',
'ItemStock' => '',
'ItemPrice' => '1716.5019',
'CostPrice' => '',
'ItemOrdered' => '1.0000',
'ItemInvoiced' => '0.0000',
'ItemSent' => '0.0000',
'CustomerID' => '1',
'BillingFirstName' => 'Brian',
'BillingLastName' => '',
'BillingCompany' => '',
'BillingE-Mail' => '',
'BillingPhone' => '',
'BillingAddress1' => '',
'BillingAddress2' => '',
'BillingCity' => '',
'BillingPostcode' => '',
'BillingState' => 'Florida',
'BillingCountry' => 'US',
'ShippingFirstName' => 'Brian',
'ShippingLastName' => '',
'ShippingCompany' => '',
'ShippingE-Mail' => '',
'ShippingPhone' => '',
'ShippingAddress1' => '',
'ShippingAddress2' => '',
'ShippingCity' => '',
'ShippingPostcode' => '',
'ShippingState' => 'Florida',
'ShippingCountry' => 'US',
'Vendor SKU' => '2P-225',
'Line Code
' => 'A1',
),
3 =>
array (
'Ordernumber' => '',
'Orderdate' => '',
'OrderStatus' => '',
'PurchasedWebsite' => '',
'PaymentMethod' => '',
'ShippingMethod' => '',
'Subtotal' => '',
'ShippingCost' => '',
'GrandTotal' => '',
'TotalTax' => '',
'TotalPaid' => '',
'TotalRefunded' => '',
'ItemName' => '',
'ItemSKU' => '',
'ItemISBN' => '',
'ItemStock' => '',
'ItemPrice' => '',
'CostPrice' => '',
'ItemOrdered' => '',
'ItemInvoiced' => '',
'ItemSent' => '',
'CustomerID' => '',
'BillingFirstName' => '',
'BillingLastName' => '',
'BillingCompany' => '',
'BillingE-Mail' => '',
'BillingPhone' => '',
'BillingAddress1' => '',
'BillingAddress2' => '',
'BillingCity' => '',
'BillingPostcode' => '',
'BillingState' => '',
'BillingCountry' => '',
'ShippingFirstName' => '',
'ShippingLastName' => '',
'ShippingCompany' => '',
'ShippingE-Mail' => '',
'ShippingPhone' => '',
'ShippingAddress1' => '',
'ShippingAddress2' => '',
'ShippingCity' => '',
'ShippingPostcode' => '',
'ShippingState' => '',
'ShippingCountry' => '',
'Vendor SKU' => '',
'Line Code
' => '',
),
);
When I attempt to echo $results['Vendor SKU'], or var_dump it.. the result is NULL even though I see a value set above. I also notice there is a syntax error at the top ('$ = array').
That being said, I'm ultimately just trying to get the values from the CSV because some of these values will be used to send order information to a third party vendor.
Can anyone point me in the right direction of how to fix my output so that I'll be able to echo the values correctly?
Thanks!
use the built in php function to parse your csv file rather than re-invent the wheel.
str_getcsv
http://php.net/manual/en/function.str-getcsv.php
There's a good example on the man page that essentially does what you want:
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
print_r($data);
Simple, use the preset CSV reading method:
$fp = fopen('data.csv', 'r');
$rows = array();
while (($row = fgetcsv($fp)) !== false)
$rows[] = $row;
fclose($fp);
$rows will then contain all data of data.csv as a two-dimensional array.
See fgetcsv() for more info.

PHP Multi-Dimensional Arrays Issue

Ok I have a mult-dimensional array which has the following structure...
0 =>
array (
'membership' =>
array (
'member' =>
array (
'name' => '',
'landline' => '',
'libcard' => '',
'mobile' => '',
'email' => '',
),
'updated_at' => '',
'member_id' => 12345,
'starts_at' => '',
'id' => 14,
'group_id' => 280,
'optional_field_values' =>
array (
0 =>
array (
'optional_field' =>
array (
'name' => '',
'updated_at' => '',
'id' => 1,
'group_id' => 280,
'description' => '',
'created_at' => '',
),
'updated_at' => '',
'optional_field_id' => 1,
'membership_id' => 14,
'id' => 4,
'value' => '12539267',
'created_at' => '',
),
),
'ends_at' => '',
'joining_fee' => 0,
'created_at' => '',
),
),
Now I can access everything inside Membership and inside Member using code like...
$member[0]['membership']['member']['name']
or
$member[0]['membership']['joining_fee']
But when ever I try to access stuff inside optional_field_values I get nothing returned...
Any ideas why this is not working?
Edit:
Trying to access the field using code like...
$member[0]['membership']['optional_field_values']['value']
$member[0]['membership']['optional_field_values'][0]['value']
^ Should work...
(Edited to match OP's edit)
How about :
$member[0]['membership']['optional_field_values'][0]['value']
You can iterate over all optional field values like this :
foreach ($member[0]['membership']['optional_field_values'] as $field)
echo $field['value'];

Categories