Push Array into another Array PHP - php

I would like to push this:
"serialNumber" => $serial,
Inside product array of $postArray and
"note" => array(
"text" => $note
),
before reservationDate Inside $postArray.
$postArray = array(
"reservationDate" => $timeData,
"emailLanguageCode" => "it_it",
"shipToCode" => $_POST['ship'],
"customer" => array(
"firstName" => $_POST['firstName'],
"lastName" => $_POST['lastName'],
"emailId" => $_POST['emailId'],
"phoneNumber" => $_POST['phoneNumber'],
"address" => array(
"addressLine1" => $_POST['addressLine1'],
"city" => $_POST['city'],
"state" => $_POST['state'],
"country" => $_POST['country'],
"postalCode" => $_POST['postalCode']
)
),
"product" => array(
"productCode" => $_POST['productCode'],
"issueReported" => $_POST['issueReported']
)
);
And result that I would like:
$postArray = array(
"note" => array(
"text" => $note
),
"reservationDate" => $timeData,
"emailLanguageCode" => "it_it",
"shipToCode" => $_POST['ship'],
"customer" => array(
"firstName" => $_POST['firstName'],
"lastName" => $_POST['lastName'],
"emailId" => $_POST['emailId'],
"phoneNumber" => $_POST['phoneNumber'],
"address" => array(
"addressLine1" => $_POST['addressLine1'],
"city" => $_POST['city'],
"state" => $_POST['state'],
"country" => $_POST['country'],
"postalCode" => $_POST['postalCode']
)
),
"product" => array(
"serialNumber" => $serial,
"productCode" => $_POST['productCode'],
"issueReported" => $_POST['issueReported']
)
);
I tried this:
array_push($postArray["product"][],$numeroSerie);
Please help.

Just simply do this
$postArray['product']['serialNumber'] = $serial;

Make First Array that which array you want in product array after use array_merge
$postArray1 = array(
"note" => array(
"text" =>15
));
$postArray = array(
"reservationDate" =>1,
"emailLanguageCode" => 2,
"shipToCode" => 3,
"customer" => array(
"firstName" => 4,
"lastName" => 5,
"emailId" => 6,
"phoneNumber" => 7,
"address" => array(
"addressLine1" => 8,
"city" =>9,
"state" => 10,
"country" => 11,
"postalCode" => 12
)
),
"product" => array(
"productCode" => 13,
"issueReported" => 14
)
);
array_merge($postArray1,$postArray);

very simple, add this two line code :
// insert "serialNumber" into "product" array
$postArray['product']['serialNumber'] = $serial;
// insert "note" into begining array element
$postArray = array('note'=>array("text" => $note))+$postArray;

These two lines,
$postArray['product'] = $serial + $postArray['product'];
$postArray = $numeroSerie + $postArray ;
And that's it,
+ operator gives union of both array and offcourse will satisfy your requirement.
Give it a try, this will work.

You will Try this i think its working fine.
$data=array("note" => array("text" => $note));
$postArray= array_merge($data,$postArray);
$postArray["product"]=array_merge(array("serialNumber"=> $serial),$postArray["product"]);

Related

Construct an associative array from 2 other arrays, and linked by a common key

Problem:
I would like to combine 2 associative arrays to make one. To link these arrays, the ID key is present in both.
Input:
To retrieve my contacts with api call, I have to do 2 requests :
First to retrieve contacts with Id, and email adresse
Second to get some informations like name, city etc.
The first one return an array like this :
$contactArray = array(
array(
"CreatedAt" => "2019-04-12T11:53:26Z",
"DeliveredCount" => 0,
"Email" => "terry#example.org",
"ExclusionFromCampaignsUpdatedAt" => "2019-04-28T09:21:35Z",
"ID" => 1864410583,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-28T09:21:35Z",
"LastUpdateAt" => "2019-04-28T09:21:35Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
),
array(
"CreatedAt" => "2019-04-12T12:39:30Z",
"DeliveredCount" => 0,
"Email" => "duane#example.org",
"ExclusionFromCampaignsUpdatedAt" => "",
"ID" => 1864410588,
"IsExcludedFromCampaigns" => false,
"IsOptInPending" => false,
"IsSpamComplaining" => false,
"LastActivityAt" => "2019-04-12T12:39:30Z",
"LastUpdateAt" => "2019-04-12T12:39:30Z",
"Name" => "",
"UnsubscribedAt" => "",
"UnsubscribedBy" => ""
)
);
The second call, return an array like
$contactDataArray =
array(
array(
"ContactID" => 1864410583,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Mark"
),
array(
"Name" => "city",
"Value" => "Miami"
),
array(
"Name" => "name",
"Value" => "Terry"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410583
),
array(
"ContactID" => 1864410588,
"Data" => array(
array(
"Name" => "firstname",
"Value" => "Jane"
),
array(
"Name" => "city",
"Value" => "New York"
),
array(
"Name" => "name",
"Value" => "Duane"
),
array(
"Name" => "phone",
"Value" => "555-5555"
)
),
"ID" => 1864410588
)
);
In $contactArray, the ID key matches with ContactID key and ID key in $contactDataArray
Attempt:
I want an array formatted like this :
$output = array(
array(
"Email" => "terry#example.org",
"ID" => 1864410583,
"firstname" => "Mark",
"city" => "Miami",
"name" => "Terry",
"phone" => "555-5555"
),
array(
"Email" => "duane#example.org",
"ID" => 1864410588,
"firstname" => "Jane",
"city" => "New York",
"name" => "Duane",
"phone" => "555-5555"
)
);
I'm trying to achieve this with array_walk, but no succeed.
You can do this with foreach,
$result = [];
foreach ($contactDataArray as $key => $value) {
$ids = array_column($contactArray, "ID"); // fetching all values from contactArray
if (!empty(array_intersect([$value['ContactID'], $value['ID']], $ids))) { // checking if both satisfy the condition
$result[$key] = array_column($value['Data'], 'Value', 'Name'); // combining name and value
// searchng for key with matched ContactID
$result[$key]['Email'] = $contactArray[array_search($value["ContactID"], $ids)]['Email'];
$result[$key]['ID'] = $value["ContactID"];
}
}
Demo.
Can you please try with this?
$output = [];
for($i = 0; $i < count($contactDataArray); $i++) {
$arrIDandEmail = [
'Email' => isset($contactArray[$i]['Email']) ? $contactArray[$i]['Email'] : '',
'ID' => isset($contactDataArray[$i]['ID']) ? $contactDataArray[$i]['ID'] : ''
];
$arrData = array_column($contactDataArray[$i]["Data"], "Value", "Name");
$newArray = array_merge($arrIDandEmail, $arrData);
$output[] = $newArray;
}
For PHP >= 7.1 you can use array destructuring using list()
<?php
$output = [];
foreach ($contactDataArray as [
'ID' => $id,
'Data' => [
['Name' => $firstnameKey, 'Value' => $firstnameValue],
['Name' => $cityKey, 'Value' => $cityValue],
['Name' => $nameKey, 'Value' => $nameValue],
['Name' => $phoneKey, 'Value' => $phoneValue]
]
]) {
$output[] = [
"Email" => $contactArray[array_search($id, array_column($contactArray, 'ID'))]['Email'],
"ID" => $id,
$firstnameKey => $firstnameValue,
$cityKey => $cityValue,
$nameKey => $nameValue,
$phoneKey => $phoneValue
];
}
var_dump($output);
Demo
You can use array_walk,array_combine,array_column for the desired array as a result
$res = [];
array_walk($contactArray, function($v, $k) use ($contactDataArray,&$res)
{
$res[] = array_merge(['Email'=>$v['Email'],'ID'=>$v['ID']],
array_combine(
array_column($contactDataArray[$k]['Data'],'Name'),
array_column($contactDataArray[$k]['Data'],'Value')
)
);
});
echo '<pre>';
print_r($res);
DEMO

'MercadoPagoException' with message 'transaction_amount attribute can't be null

I am getting an error
I want to implement payment gateway but the error is much like :
Illegal string offset 'code'
Illegal string offset 'description'
'MercadoPagoException' with message 'transaction_amount attribute can't be null
This is my array
$preference_data = array(
"items" => array(
array(
"id" => "Code",
"title" => $rest['name'],
"currency_id" => "USD",
"picture_url" =>"https://www.mercadopago.com/org-img/MP3/home/logomp3.gif",
"description" => "Description",
"category_id" => "Category",
"quantity" => 1,
"unit_price" => intval($total_price)
)
),
"payer" => array(
"name" => "APRO".$a[0],
"surname" => $a[1],
"email" => "test_user_44825516#testuser.com",
"date_created" => "2014-07-28T09:50:37.521-04:00",
"phone" => array(
"area_code" => "11",
"number" => "4444-4444"
),
"identification" => array(
"type" => "DNI",
"number" => "12345678"
),
"address" => array(
"street_name" => "Street",
"street_number" => 123,
"zip_code" => "1430"
)
),
"back_urls" => array(
"success" => "http://localhost/duncan_fooddelivery/api/success.php",
"failure" => "http://www.failure.com",
"pending" => "http://www.pending.com"
),
"auto_return" => "approved",
"payment_methods" => array(
"excluded_payment_methods" => array(
array(
"id" => "amex",
)
),
"excluded_payment_types" => array(
array(
"id" => "ticket"
)
),
"installments" => 24,
"default_payment_method_id" => null,
"default_installments" => null,
),
"shipments" => array(
"receiver_address" => array(
"zip_code" => "1430",
"street_number"=> 123,
"street_name"=> "Street",
"floor"=> 4,
"apartment"=> "C"
)
),
"token" => array (
"card_id" => NULL,
"card_number_length" => 16,
"cardholder" => array (
"identification" => array (
"number" => "11111111",
"type" => "DNI",
),
"name" => "APROARPAN BAJPAI",
),
"creation_date" => NULL,
"due_date" => NULL,
"esc" => NULL,
"expiration_month" => 6,
"expiration_year" => 2022,
"first_six_digits" => "450995",
"id" => "ad56c2e6cb4a2b17c18e632139366a7e",
"last_four_digits" => "3704",
"last_modified_date" => NULL,
"luhn_validation" => "true",
"public_key" => "TEST-1a0ffe62-165f-4e7b-b501-df15741b6d87",
"security_code_length" => 3,
"status" => "active",
"trunc_card_number" => NULL,
"used_date" => NULL,
),
"transaction_amount" => 60,
"notification_url" => "https://www.your-site.com/ipn",
"external_reference" => "Reference_1234",
"expires" => false,
"expiration_date_from" => null,
"expiration_date_to" => null,
);
I am passing "transaction_amount" => 60, But still getting same error.
Please help me I am searching from 5 Hours.
Thanks.

Cannot create order Woocommerce rest Api php

I tried the following code and tried to post values from android to place an order but every time i test it on chrome it give http 500 error, and Android gives volly server error. Dont know where i am messing up, serious help would be appriciated. Thank You
Ask me if you need to take a look at the android Code, but i think that doesnot matter here because i am giving hard coded values in $data.
<?php
require_once( 'lib/woocommerce-api.php' );
$pageNum=1;
$pageNum=$_GET['page_num'];
$options = array(
'debug' => true,
'return_as_array' => false,
'validate_url' => false,
'timeout' => 30,
'ssl_verify' => false,
);
try {
$client = new WC_API_Client( 'https://www.move2mart.com/', 'ck_0afa3a49305683160fe34189553a660053bd4e6239', 'cs_7dc38a7b52c3fdd34qw61e34090be636ae3364b196', $options );
//$data=array();
$data=[
'payment_method' => 'cod',
'payment_method_title' => 'Cash on Delivery',
'set_paid' => false,
'billing' => [
'first_name' => 'John',
'last_name' => 'Doe',
'address_1' => '969 Market',
'city' => 'Karachi',
'email' => 'princeali#testing.com',
'phone' => '03123121995'
], 'line_items' => [
[
'product_id' => 779,
'quantity' => 1
]
]
];
print_r($client->post('orders', $data));
if($_POST !=null) {
}
else{
echo "Null POST Request";
}
} catch ( WC_API_Client_Exception $e ) {
echo $e->getMessage() . PHP_EOL;
echo $e->getCode() . PHP_EOL;
if ( $e instanceof WC_API_Client_HTTP_Exception ) {
print_r( $e->get_request() );
print_r( $e->get_response() );
}
}
$orderData = array(
"order" => array(
"billing_address" => array(
array(
"first_name" => "",
"last_name" => "",
"company" => "",
"address_1" => "",
"address_2" => "",
"city" => "",
"state" => "",
"postcode" => "",
"country" => "",
"email" => "",
"phone" => "",
)
),
"shipping_address" => array(
array(
"first_name" => "",
"last_name" => "",
"company" => "",
"address_1" => "",
"address_2" => "",
"city" => "",
"state" => "",
"postcode" => "",
"country" => "",
)
),
"customer_id" => 1,
"line_items" => array(
array(
"product_id" => 1,
"quantity" => 1
)
)
)
);
$client->orders->create($orderData);
Would you please try above code?
Finally, I figured it out after some research. Below is working code of woocommerce checkout webservice that may Help you -
/*** Just Copy & Paste and change your varriables **/
//do your initial stuff
header('Content-type: application/json');
$json_file=file_get_contents('php://input');
$jsonvalue= json_decode($json_file,true);
$user_id = $jsonvalue['user_id'];
$product_id = $jsonvalue['product_id'];
$quantity = $jsonvalue['quantity'];
//start order data
$orderData = array(
"order" => array(
'payment_method' => 'paypal',
'payment_method_title' => 'Paypal',
'set_paid' => true,
"billing_address" => array(
"first_name" => "bfname",
"last_name" => "blname",
"company" => "testcompanybilling",
"address_1" => "sec8",
"address_2" => "e32",
"city" => "noida",
"state" => "Noida",
"postcode" => "99999",
"country" => "IN",
"email" => "test#gmail.com",
"phone" => "888899999999"
),
"shipping_address" => array(
"first_name" => "sfname",
"last_name" => "slname",
"company" => "testcompanyshipping",
"address_1" => "shakkarpur",
"address_2" => "laxminigar",
"city" => "New Delhi",
"state" => "Delhi",
"postcode" => "110092",
"country" => "IN",
"email" => "testsh#gmail.com",
"phone" => "11009999"
),
"customer_id" => $user_id,
"line_items" => array(
array(
"product_id" => $product_id,
"quantity" => $quantity
)
),
'shipping_lines' => array(
array(
'method_id' => 'flat_rate',
'method_title' => 'Flat Rate',
'total' => 10
)
)
)
);
//Create order usind order data
$data = $client->orders->create($orderData);
//echo '<pre>';
//print_r($data);
$result['success']='true';
$result['error']="0";
$result['msg']='Your order has been successfully placed.';
$result['data']=$data;
echo json_encode($result); `
cheers!!!

2checkout api call for create sale

I am using 2checkout api for my website product sale. Hence I am calling 2checkout api to create sale where I can call api with total amount with a single product.It's look like flowing:
try {
$charge = Twocheckout_Charge::auth(array(
"merchantOrderId" => "123",
"token" => $_POST['token'],
"currency" => 'USD',
"total" => $first_bill['amount'],
"billingAddr" => array(
"name" => $_POST['b_name'],
"addrLine1" => $_POST['b_address'],
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => $_POST['b_country'],
"email" => $_POST['b_emaill'],
"phoneNumber" => $_POST['b_phone']
),
"shippingAddr" => array(
"name" => 'Testing Tester',
"addrLine1" => '123 Test St',
"city" => 'Columbus',
"state" => 'enter code hereOH',
"zipCode" => '43123',
"country" => 'USA',
"email" => 'example#2co.com',
"phoneNumber" => '555-555-5555'
)
));
if ($charge['response']['responseCode'] == 'APPROVED') {
echo $response;exit;
// echo "Thanks for your Order!";
// echo "<h3>Return Parameters:</h3>";
// echo "<pre>";
// print_r($charge);
// echo "</pre>";
}
else
{
$this->Registrationmodel->delete_account($accounts_id);
echo $charge['response']['responseCode'];
exit;
}
}
catch (Twocheckout_Error $e)
{
echo $e->getMessage();
exit;
}
}
hence when i try to set line items individual like following:
try {
$charge = Twocheckout_Charge::auth(array(
"merchantOrderId" => "123",
"token" => $_POST['token'],
"currency" => 'USD',
//"total" => $first_bill['amount'],
"billingAddr" => array(
"name" => $_POST['b_name'],
"addrLine1" => $_POST['b_address'],
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => $_POST['b_country'],
"email" => $_POST['b_emaill'],
"phoneNumber" => $_POST['b_phone']
),
"LineItem" => array(
"duration" => 'Forever',
"price" => '10',
"productId" =>'1235',
"quantity" => '1',
"recurrence" => '1 Month',
"tangible" => 'N',
"type"=>'product'
),
"shippingAddr" => array(
"name" => 'Testing Tester',
"addrLine1" => '123 Test St',
"city" => 'Columbus',
"state" => 'OH',
"zipCode" => '43123',
"country" => 'USA',
"email" => 'example#2co.com',
"phoneNumber" => '555-555-5555'
)
));
if ($charge['response']['responseCode'] == 'APPROVED') {
$response = $this->return_information($charge['response']['orderNumber']);
echo $response;exit;
// echo "Thanks for your Order!";
// echo "<h3>Return Parameters:</h3>";
// echo "<pre>";
// print_r($charge);
// echo "</pre>";
}
else
{
$this->Registrationmodel->delete_account($accounts_id);
echo $charge['response']['responseCode'];
exit;
}
}
catch (Twocheckout_Error $e)
{
$this->Registrationmodel->delete_account($accounts_id);
echo $e->getMessage();
exit;
}
}
It is giving me parameter error. Please can anyone help ? how to set line items using api call?
Your lineitem array is missing the 'name' param, which is a required parameter. A full list of required params can be located here .
Also your shipping array is unnecessary as your product is intangible, therefore you could remove the shipping array.
Here's a working example I use:
try {
$charge = Twocheckout_Charge::auth(array(
"sellerId" => "xxxxxxxxx",
"li_0_merchant_order_id" => "1",
"type" => "product",
"token" => $_POST['token'],
"currency" => "USD",
// "total" => "1.00", //Only use when lineitems are not passed in
"lineItems" => array(
"0" => array(
"name" => $_POST['name'],
"price" => $_POST['price'],
"quantity" => $_POST['quantity'],
"startupFee" => $_POST['startupFee'],
"tangible" => $_POST['tangible']
)
),
"billingAddr" => array(
"name" => $_POST['customer'],
"addrLine1" => $_POST['addrLine1'],
"city" => $_POST['city'],
"state" => $_POST['state'],
"zipCode" => $_POST['zipCode'],
"country" => $_POST['country'],
"email" => $_POST['email'],
"phoneNumber" => ''
)
));
if ($charge['response']['responseCode'] == 'APPROVED') {
To better fit your app, add the "duration" & "recurrence" keys & their respective values to the lineItem array in the code I provided above. The example I provided contains all required parameters for a non-tangible sale.

if statement in an array

I have a array I have to post (json). But the value accountNr should either be $val_nc_iban or should be NULL depending on a certain value outside this array. So how can I either echo $val_nc_iban (is a string) or NULL (not string) inside an array depending on the outside value?
$curl_post_data_nc = array(
"person" => array(
"title" => "$val_nc_persontitle",
"nationalNr" => NULL,
"firstName" => "$val_nc_personfirstname",
"lastName" => "$val_nc_personsurname",
"birthDate" => "$new_val_nc_persondob"
),
"company" => array(
"type" => "$val_nc_companytype",
"name" => "$val_nc_companyname",
"vat" => "$val_nc_companyvat",
"nace" => "$val_nc_companynace",
"website" => NULL
),
"contact" => array(
"email" => "$val_nc_personemail",
"mobile" => "$val_nc_personphone",
"telephone" => NULL
),
"contract" => array(
"referenceDate" => "$val_nc_refdate",
"startDate" => "$val_nc_startdate"
),
"payment" => array(
"paymentMethodEmail" => false,
"paymentMethodMail" => true,
"paymentInterval" => "$val_nc_paymentbilling",
"method" => "$val_nc_paymentmethod",
"accountNr" => $val_nc_result = ($val_nc_paymentmethod == 'TRANSFER') ? NULL : "$val_nc_iban"
),
"deliveryAddress" => array(
"building" => "HOUSE",
"street" => "$val_nc_personstreet",
"streetNr" => "$val_nc_personstreetnr",
"floor" => NULL,
"boxNr" => NULL,
"localityCode" => "$val_nc_personpostcode",
"localityName" => "$val_nc_personlocality"
),
"invoiceAddress" => array(
"sameAsDelivery" => false,
"building" => "HOUSE",
"street" => "$val_nc_billstreet",
"streetNr" => "$val_nc_billstreetnr",
"floor" => NULL,
"boxNr" => NULL,
"localityCode" => "$val_nc_billpostcode",
"localityName" => "$val_nc_billlocality"
),
"gasMeter" => array(
"ean" => "$val_nc_ean",
"nr" => NULL,
"type" => "gas",
"electric" => NULL,
"gas" => array(
"usage" => $val_nc_gasusage,
"formula" => "TTF103532"
)
),
Why do you put the variables in quotes? You can use their actual value in the array!
Example:
$curl_post_data_nc = array(
"person" => array(
"title" => $val_nc_persontitle,
"nationalNr" => NULL,
"firstName" => $val_nc_personfirstname,
"lastName" => $val_nc_personsurname,
"birthDate" => $new_val_nc_persondob
),
"company" => array(
"type" => $val_nc_companytype,
"name" => $val_nc_companyname,
"vat" => $val_nc_companyvat,
"nace" => $val_nc_companynace,
"website" => NULL
),
"contact" => array(
"email" => $val_nc_personemail,
"mobile" => $val_nc_personphone,
"telephone" => NULL
),
"contract" => array(
"referenceDate" => $val_nc_refdate,
"startDate" => $val_nc_startdate
),
"payment" => array(
"paymentMethodEmail" => false,
"paymentMethodMail" => true,
"paymentInterval" => $val_nc_paymentbilling,
"method" => $val_nc_paymentmethod,
"accountNr" => $val_nc_result = ($val_nc_paymentmethod == 'TRANSFER') ? NULL : $val_nc_iban
),
"deliveryAddress" => array(
"building" => "HOUSE",
"street" => $val_nc_personstreet,
"streetNr" => $val_nc_personstreetnr,
"floor" => NULL,
"boxNr" => NULL,
"localityCode" => $val_nc_personpostcode,
"localityName" => $val_nc_personlocality
),
"invoiceAddress" => array(
"sameAsDelivery" => false,
"building" => "HOUSE",
"street" => $val_nc_billstreet,
"streetNr" => $val_nc_billstreetnr,
"floor" => NULL,
"boxNr" => NULL,
"localityCode" => $val_nc_billpostcode,
"localityName" => $val_nc_billlocality
),
"gasMeter" => array(
"ean" => $val_nc_ean,
"nr" => NULL,
"type" => "gas",
"electric" => NULL,
"gas" => array(
"usage" => $val_nc_gasusage,
"formula" => "TTF103532"
)
),

Categories