send post json with php (curl) - php

i done search tutorial for send post json with curl ..
but for this value i cant find in here..
and my question how to convert to array post json in value if like
this, and this my value post json
{
"payment_type": "bca_klikpay",
"transaction_details": {
"order_id": "orderid-01",
"gross_amount": 11000
},
"item_details": [
{
"id": "1",
"price": 11000,
"quantity": 1,
"name": "Mobil "
}
],
"customer_details":{
"first_name": "John",
"last_name": "Baker",
"email": "john.baker#email.com",
"phone": "08123456789"
},
"bca_klikpay": {
"description": "Pembelian Barang"
}
}
i done try to php array like this but still error
$item = array('id' => 'id1', 'price' => 11000, 'quantity' => 1 , 'name' => 'Mobil');
$data2 =array('payment_type' => 'bca_klikpay',
'transaction_details' => array('order_id' => 'orderid-01', 'gross_amount' => 11000),
'item_details' => array([$item]),
'customer_details'=> array('first_name' => 'john',
'last_name' => 'baker', 'email' => 'john.baker#email.com', 'phone' => 08123456789),
'bca_klikpay' => array('description' => 'Pembelian Barang'));
maybe someone can help me.. and sory for my bad english
thanks

There is the following error - the phone number has to be string, not number, so it would look like this 'phone' => '08123456789', because numbers cannot begin with 0.
Beside this, there is the following issue - You should not set item_details like this, but rather 'item_details' => [$item]. You do not need 2 nested arrays, just one. (array() is equal to []. They are practically the same in your use case. So you are doing something like array(array($item)), which is wrong)
What else, you have to do a $json = json_encode($data2); at the end and it will return what you want it to.

Related

How do i merge these arrays into one [duplicate]

This question already has answers here:
Merge two arrays into one associative array
(2 answers)
Closed 7 months ago.
I want to change the following php array
"extra_charge_item" => [
0 => "Massage",
1 => "Pool table",
2 => "Laundry"
],
"extra_charge_description" => [
0 => "Paid",
1 => "Paid",
2 => "We wash everything"
],
"extra_charge_price" => [
0 => "200",
1 => "100",
2 => "1000"
],
I haven't been able to solve for a whole 2hrs
This is the expected output
"new_data" => [
0 => [
"Maasage", "Paid", "200"
],
1 => [
"Pool table", "Paid", "100"
],
2 => [
"Laundry", "we wash everything", "1000"
]
]
Rather than doing all the work for you, here's some pointers on one way to approach this:
If you are happy to assume that all three sub-arrays have the same number of items, you can use array_keys to get those keys from whichever you want.
Once you have those keys, you can use a foreach loop to look at each in turn.
For each key, use square bracket syntax to pluck the three items you need.
Use [$foo, $bar, $baz] or array($foo, $bar, $baz) to create a new array.
Assign that array to your final output array, using the key from your foreach loop.
Just use foreach with key => value
$data = [
"extra_charge_item" => [
0 => "Massage",
1 => "Pool table",
2 => "Laundry"
],
"extra_charge_description" => [
0 => "Paid",
1 => "Paid",
2 => "We wash everything"
],
"extra_charge_price" => [
0 => "200",
1 => "100",
2 => "1000"
],
];
$newData = [];
foreach ($data as $value) {
foreach ($value as $k => $v) {
$newData[$k][] = $v;
}
}
var_dump($newData);
I found an answer. Seems someone else had the same problem
Merge two arrays into one associative array
Here's the solution for my case;
//These are arrays passed from front end in the name attribute e.g extra_charge_item[] e.t.c
$extra_charge_item_array = $request->input('extra_charge_item');
$extra_charge_description_array = $request->input('extra_charge_description');
$extra_charge_price_array = $request->input('extra_charge_price');
$new_extra_charges_data = array_map(
function ($item, $description, $price) {
return [
'item' => $item,
'description' => $description,
'price'=> $price
];
}, $extra_charge_item_array, $extra_charge_description_array, $extra_charge_price_array);
//save the data
foreach ($new_extra_charges_data as $extra_charge) {
Charge::create([
'item' => $extra_charge['item'],
'description' => $extra_charge['description'],
'price' => $extra_charge['price']
]);
}

How can I build an object/array?

I am rather new to PHP so I don't know how to work with these datasets. I make a MySQL select and get back an object like this:
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 1,
"dailyworkhourssum": "7.70"
},
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 3,
"dailyworkhourssum": "1.2"
},
{
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": "7.70"
},
I want to iterate through this and in the end it should look like this:
{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid1": true,
"categorid3": true,
"dailyworkhourssum1": "7.70",
"dailyworkhourssum3": "1.2"
},
{
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": "7.70"
},
What this does is that it merges tow fields together (if they have the same bookingdate )into one so that I can display it in a table without reoccurring dates.
My problem:
I don't know what this type of data is called.
I don't know how to create something like this.
I can add fields to this type of data with $data->newField = example so I think that this is an object.
In JS it's called an object, but in PHP you will use an associative array instead.
In your case, I think, you have an array of associative arrays. It looks like this:
$books = [
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 1,
"dailyworkhourssum" => "7.70"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-03",
"categoryid" => 3,
"dailyworkhourssum" => "1.2"
],
[
"membername" => "NAME",
"bookingdate" => "2020-02-05",
"categoryid" => 3,
"dailyworkhourssum" => "7.70"
]
];
If you wanna merge an arrays with the same "bookingdate" then I recommend you to loop through this array and add its elements to another associative array with bookingdates as keys, and check, in case if there is such key already, then merge the arrays, like this:
$merged = [];
foreach ($books as $book) {
$date = $book['bookingdate'];
if (isset($merged[$date])) {
$merged[$date] = $merged[$date] + $book;
} else {
$merged[$date] = $book;
}
}
I think that it is not a valid code (no time, sorry), but I hope, you cautch the idea.
If you want a 'list' instead of an associative array, than you can do this:
$mergedList = array_values($merged);
Thus you will rid of string keys.
If I understood correctly, you obtain a table with 4 columns an a variable number of rows and you want to transform it to a table with a variable number of columns. For that, using a data structure where every item is different from the previous one can make everything harder than it needs. I'd suggest you use a fixed structure:
// I'm assuming you have a PHP array as starting point
$input = [
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 1,
'dailyworkhourssum' => '7.70',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-03',
'categoryid' => 3,
'dailyworkhourssum' => '1.2',
],
[
'membername' => 'NAME',
'bookingdate' => '2020-02-05',
'categoryid' => 3,
'dailyworkhourssum' => '7.70',
],
];
$output = [];
foreach ($input as $data) {
// We'll group by booking date
if (!isset($output[$data['bookingdate']])) {
$output[$data['bookingdate']] = [
'membername' => $data['membername'],
'bookingdate' => $data['bookingdate'],
'categoryid' => $data['categoryid'],
'dailyworkhourssum' => [],
];
}
// A single date may have several daily work hours
$output[$data['bookingdate']]['dailyworkhourssum'][] = $data['dailyworkhourssum'];
}
// We discard array keys (we only needed them to group)
echo json_encode(array_values($output));
[{
"membername": "NAME",
"bookingdate": "2020-02-03",
"categoryid": 1,
"dailyworkhourssum": ["7.70", "1.2"]
}, {
"membername": "NAME",
"bookingdate": "2020-02-05",
"categoryid": 3,
"dailyworkhourssum": ["7.70"]
}]
Wherever you consume this JSON you just need to loop the dailyworkhourssum array. You may also want to loop the entire structure before printing the table and keep a counter in order to determine the maximum number of columns so you can draw empty cells where needed (tables are rectangular).

Insert array into another array based on if command - putting it in wrong place

I have this array:
$arr = array(
'reportDescription' => array(
'reportSuiteID' => 'globretailprod',
'elements' => array(
0 => array(
'id' => $queryElement
)
),
'metrics' => array(
0 => array(
'id' => $queryMetric
)
)
)
);
I'm trying to insert some code into the array using an if command. This is what I have:
if (isset($querySegment)) {
$arr['reportDescription']['segments'] = $querySegment;
}
However that gives me the wrong result, what I am trying to achieve is this:
{
"reportDescription": {
"reportSuiteID": "rbsglobretailprod",
"dateFrom": "2018-09-09",
"dateTo": "2018-09-10",
"dateGranularity": "day",
"metrics": [{
"id": "pageviews"
}],
"elements": [{
"id": "page"
}],
"segments": [{
"id": "jjj"
}]
}
}
Notice there are two issues with this. Firstly, segments isn't isn't insert with an id, it's just inserted as a value. Secondly, I am a bit concerned about the trailing comma after metrics in my original array, since I need to be able to add a comma after the metrics array if I do include segments.
Just use the same format as you use for the other items to get the same structure...
if (isset($querySegment)) {
$arr['reportDescription']['segments'] = array(
0 => array(
'id' => $querySegment
)
);
}
As for the comma, this should be added automatically as needed if your using json_encode()

json_encode for flot chart

I am stumped on producing a specifically formatted JSON for a flot chart. Any help is much appreciated!
I use this php code
$query = mysql_query('SELECT * FROM all_programs_extended');
while($row = mysql_fetch_assoc($query)) {
$newData[] = array(
'label' => $row['program_type'],
'data' => array(
"employee1" => $row['employee1'],
"employee2" => $row['employee2'],
"employee3" => $row['employee3']
)
);
}
print json_encode($newData);
which produces this valid JSON
[{"label":"Program A","data":{"employee1":"5","employee2":"3","employee3":"1"}},
{"label":"Program B","data":{"employee1":"0","employee2":"4","employee3":"2"}},
{"label":"Program A","data":{"employee1":"4","employee2":"2","employee3":"4"}}]
but I need it look like this:
{
"label": "Program A",
"data": [[employee1, 5], [employee2, 3], [employee3, 1]],
"label": "Program B",
"data": [[employee1, 0], [employee2, 4], [employee3, 2]],
"label": "Program C",
"data": [[employee1, 4], [employee2, 2], [employee3, 4]]
}
I seem to have mixed up by brackets and braces, and I also need a comma separating my value pairs between brackets rather than the colon in the first JSON. Be nice to get ride of the quotation marks around the numbers too!
Thanks very much!
Just suround employeeX by an additional array:
$newData[] = array(
'label' => $row['program_type'],
'data' => array(
array(
"employee1" => $row['employee1']
),
array (
"employee2" => $row['employee2']
),
array (
"employee3" => $row['employee3']
)
)
);

Nested PHP arrays to json

So my code here:
$featurecollection = ("FeatureCollection");
$test[] = array (
"type" => $featurecollection,
$features[] = array($images)
);
file_put_contents($cache,json_encode($test));
results in the following json:
[
{
"type":"feature",
"0":[
[
{
"title":"some title",
"src":"value",
"lat":"value",
"lon":"value"
},
{
"title":"some title",
...
But I need to nest things differently and I'm perplexed on how the php array should be constructed in order to get a result like:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":{
"coordinates":[
-94.34885,
39.35757
],
"type":"Point"
},
"properties":{
"latitude":39.35757,
"title":"Kearney",
"id":919,
"description":"I REALLY need new #converse, lol. I've had these for three years. So #destroyed ! :( Oh well. Can't wait to get a new pair and put my #rainbow laces through. #gay #gaypride #bi #proud #pride #colors #shoes #allstar #supporting ",
"longitude":-94.34885,
"user":"trena1echo5",
"image":"http://images.instagram.com/media/2011/09/09/ddeb9bb508c94f2b8ff848a2d2cd3ece_7.jpg",
"instagram_id":211443415
}
},
What would the php array look like for that? I'm thrown off by the way everything is nested but still has a key value.
Here's how I'd represent that in PHP:
array(
'type' => 'FeatureCollection',
'features' => array(
array(
'type' => 'Feature',
'geometry' => array(
'coordinates' => array(-94.34885, 39.35757),
'type' => 'Point'
), // geometry
'properties' => array(
// latitude, longitude, id etc.
) // properties
), // end of first feature
array( ... ), // etc.
) // features
)
So to get that structure, each feature has to be an associative array of:
type,
geometry - an associative array of:
coordinates - an indexed array of values,
type
properties - an associative array of values like latitude, longitude, id etc.
It's times like these when I prefer languages that distinguish between lists (array(1, 2, 3)) and dictionaries or maps (array('a' => 1, 'b' => 2)).
With PHP 5.4 and above:
$array = [
'type' => 'FeatureCollection',
'features' => [
[
'type' => 'Feature',
'geometry' => [
'coordinates' => [-94.34885, 39.35757],
'type' => 'Point'
], // geometry
'properties' => [
// latitude, longitude, id etc.
] // properties
], // end of first feature
[] // another feature, and so on
] // end of features
];
For the PHP script below:
<?php
header('Content-type=> application/json');
echo json_encode($array);
This is the JSON output;
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"coordinates": [
-94.34885,
39.35757
],
"type": "Point"
},
"properties": []
},
[]
]
}

Categories