Formatting data in HTTP POST request with PHP - php

I'm using an API which gives an example of how they want the data of the POST request I'm about to make to be formatted. This is their example:
un=chris&
key=xxxx&
origin=plot&
platform=lisp&
args=[[0, 1, 2], [3, 4, 5], [1, 2, 3], [6, 6, 5]]&
kwargs={"filename": "plot from api",
"fileopt": "overwrite",
"style": {
"type": "bar"
},
"traces": [1],
"layout": {
"title": "experimental data"
},
"world_readable": true
}
I'm confused about how I should put together this data from existing arrays in PHP. From what I understand the example show an encoded "string" that is just partly encoded? As of now I am putting the string together all by myself through extracting the keys and values from the arrays.
I'm looking for a more neat way of doing this with existing methods?

I believe using http_build_query will solve this for you.
Given the example, here's sample of how to use it:
$args = array(array(0,1,2), array(3,4,5), array(1,2,3), array(6,6,5));
$kwargs = array(
'filename' => 'plot from api',
'fileopt' => 'overwrite'
'style' => array('type' => 'bar'),
'traces' => array(1),
'layout' => array('title' => 'experimental data'),
'word_readable' => true
);
$request = array(
'un' => 'chris',
'key' => 'xxx',
'origin' => 'plot',
'platform' => 'lisp',
'args' => $args,
'kwargs' => $kwargs
);
$queryString = http_build_query($request);
echo $queryString;
More info: https://php.net/http_build_query

Related

How can I manage some irregular array to regular array?

I write code with some array that have different structure, but I must extract the data to do something else. How can I manager these array?
The array's structure are as follow:
$a = [
'pos1' => 'somedata',
'pos2' => ['data2', 'data3'],
'pos3' => '';
];
$b = [
[
'pos1' => ['data1', 'data2', ['nest1', 'nest2']],
'pos2' => ['data1', 'data2', 'data3'],
],
['data1', 'data2'],
'data4',
];
The array's Index can be a key or a position, and the value of the corresponding index may be a array with the same structure. More tough problem is that the subarray can be nesting, and the time of the nesting has different length.
Fortunately, every array has it's owe fixed structure.
I want to convert the these array to the format as follow. When the index is a value, change it to the keyword; and if the index is a keyword, nothing changed.
$a = [
'pos1' => 'somedata',
'pos2' => [
'pos2_1' => 'data2',
'pos2_2' => 'data3'
],
'pos3' => '';
];
$b = [
'pos1' => [
'pos1_1' => [
'pos1_1_1' => 'data1',
'pos1_1_2' => 'data2',
'pos1_1_3' => [
'pos1_1_3_1' => 'nest1',
'pos1_1_3_2' => 'nest2',
],
],
'pos1_2' => [
'pos1_2_1' => 'data1',
'pos1_2_2' => 'data2',
'pos1_2_3' => 'data3',
],
],
'pos2' => ['data1', 'data2'],
'pos3' => 'data4',
];
My first solution is for every array, write the function to convert the format(the keyword will specify in function). But it is a huge task and diffcult to manage.
The second solution is write a common function, with two argument: the source array and the configuration that specify the keyword to correspondent value index. For example:
$a = [0, ['pos10' => 1]];
$conf = [
// It means that when the value index is 0, it will change it into 'pos1'
'pos1' => 0,
'pos2' => 1,
];
The common funciton will generate the result of:
$result = [
'pos1' => 0,
'pos2' => ['pos10' => 1],
]
But this solution will lead to a problem: the config is diffcult to understand and design, and other people will spend a lot of time to understand the format after conversion.
Is there are some better solution to manage these array that other people can easy to use these array?
Thanks.

Merging and array of arrays with the same keys

So I found an answer which is supposed to work, however it doesn't appear too...
Already accepted answer with the same issue.
I have got the following array called $banners:
[
0 => [
"bannerCustomTemplate" => 0,
"bannerId" => 1,
"bannerType" => 1,
"bannerTitle" => "Merry",
"bannerStrapline" => "Christmas",
"bannerPeriod" => "2018-12-01 to 2018-12-10",
"bannerText" => "Christmas opening hours"
],
1 => [
"bannerCustomTemplate" => 0,
"bannerId" => 7,
"bannerType" => 2,
"bannerTitle" => "Easter",
"bannerStrapline" => "Test",
"bannerPeriod" => "2018-12-04 to 2018-12-12",
"bannerText" => "dsadasdaas"
]
]
The answers I have read suggest $all_banners = call_user_func_array('array_merge', $banners);.
However this is giving me:
[
"bannerCustomTemplate" => 0,
"bannerId" => 7,
"bannerType" => 2,
"bannerTitle" => "Easter",
"bannerStrapline" => "Test",
"bannerPeriod" => "2018-12-04 to 2018-12-12",
"bannerText" => "dsadasdaas"
]
Seems like it's just replacing rather than merging. Anyone got any ideas?
Edit
Just read the following comment
Little note here. The updated variant with unpacking array doesn't work with string keys. But the first one works perfect. Just keep in mind this. – Alliswell
So I have now updated my code with another solutions, with the same results.
Edit 2
Well, merging is merging not replacing. So what I expect is:
[
"bannerCustomTemplate" => [ 0, 0 ],
"bannerId" => [ 1, 7 ],
"bannerType" => [ 1, 2 ],
"bannerTitle" => [ "Merry", "Easter" ]
"bannerStrapline" => [ "Christmas", "Test" ]
"bannerPeriod" => [ "2018-12-01 to 2018-12-10", "2018-12-04 to 2018-12-12" ]
"bannerText" => ["Christmas opening hours", "dsadasdaas" ]
]
If all your arrays are known to contain the same keys in the same order, this is probably easiest:
$data = [
['foo' => 'bar', 'baz' => 42],
['foo' => 'baz', 'baz' => 69]
];
$result = array_combine(array_keys($data[0]), array_map(null, ...$data));
This uses the useful behaviour of array_map with null as the callback to take one element from each input array and return a new combined array.

change "0" to names in Json file

I am using PHP array and outputing to JSON string. I want to convert "0" in the json format to lets say calling them "items". Since while importing this to oracle db it says expecting names instead of zero. When I change the index ( 0, 1, 2 ) to be called just items, it works normally.
Here is the PHP array, and I am outputting it as json.
$data = array(
'INDIVIDUAL_SALUTATION' => $salution,
'INDIVIDUAL_FIRST_NAME' => $firstname,
'INDIVIDUAL_LAST_NAME' => $lastname,
'GENDER' => $gender,
'DATE_OF_BIRTH' => $result['Birthday'],
'EMAIL_ID' => $result['Email'],
'MOBILE_NUMBER' =>$result['Phone'],
'MOBILE_COUNTRY_CODE' => substr($result['Phone'], 1, 3),
'OCCUPATION' => null,
'OCCUPATION_STATUS' => null,
'ADDRESS_LINE1' => $result['Address_street'],
'TOWN' => $result['Address_city'],
'POSTAL_CODE' => $result['Address_zip'],
'COUNTRY' => $result['country_name'],
'CUSTOMER_NUMBER' => $result['Owner'],
'POLICY_START_DATE' => $result['paid_thru_date'],
'POLICY_END_DATE' => $result['duedate'],
'LOAN_AGREEMENT_NUMBER' => $result['ORIG_ID'],
'REPAYABLE_AMOUNT' => $result['repayable_amount'],
'FINANCE_TERM_MONTHS' => $result['finance_term_months'],
'MONTHLY_INSTALLMENT' => $result['monthly_installment'],
'AMOUNT_INSURED' => $result['amount_insured'],
'CURRENCY_ID' => $result['Abbreviation']
);
$jsonArray[] = $data;
}
$mainInfo = array(
'SRC_NAME' => 'AEX',
"RUN_NUMBER" => 1,
"RUN_DATE" => date("Ymd"),
"RUN_NO_OF_RECORDS" => $arrayCount,
"YTD_NO_OF_RECORDS" => $arrayCount
);
$finalArray = array_merge($jsonArray , $mainInfo);
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($finalArray));
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($mainInfo));
Here is the output
{
"0":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"three",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowerthree#aurorax.co",
"MOBILE_NUMBER":"+3581466144569",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"772",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"7",
"REPAYABLE_AMOUNT":"50.42",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"8.40",
"AMOUNT_INSURED":"50.42",
"CURRENCY_ID":"EUR"
},
"1":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"three",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowerthree#aurorax.co",
"MOBILE_NUMBER":"+3581466144569",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"772",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"9",
"REPAYABLE_AMOUNT":"40.35",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"6.73",
"AMOUNT_INSURED":"40.35",
"CURRENCY_ID":"EUR"
},
"2":{
"INDIVIDUAL_SALUTATION":"MR",
"INDIVIDUAL_FIRST_NAME":"borrower",
"INDIVIDUAL_LAST_NAME":"two",
"GENDER":"M",
"DATE_OF_BIRTH":"1993-09-17",
"EMAIL_ID":"borrowertwo#aurorax.co",
"MOBILE_NUMBER":"+358466144569123",
"MOBILE_COUNTRY_CODE":"358",
"OCCUPATION":null,
"OCCUPATION_STATUS":null,
"ADDRESS_LINE1":"Vaskivuorentie 22B",
"TOWN":"Vantaa",
"POSTAL_CODE":"01600",
"COUNTRY":"Finland",
"CUSTOMER_NUMBER":"770",
"POLICY_START_DATE":"2017-01-02",
"POLICY_END_DATE":"2017-07-01",
"LOAN_AGREEMENT_NUMBER":"11",
"REPAYABLE_AMOUNT":"99.84",
"FINANCE_TERM_MONTHS":"6",
"MONTHLY_INSTALLMENT":"16.64",
"AMOUNT_INSURED":"99.84",
"CURRENCY_ID":"EUR"
},
"RUN_NUMBER":1,
"RUN_DATE":"20170109"
}
What I am trying to do is make it look like instead of 0 have 'items' : {} and then move on, so I can import it to oracle.
How can I achieve this with php?
Don't use array_merge, put the array in an element of $mainInfo:
$mainInfo['items'] = $jsonArray;
$this->output->set_output(json_encode($mainInfo));
Create index variable and make it to zero
$index = 0
And change this $jsonArray[] = $data; to this $jsonArray['item' .$index++] = $data;
Hope that helps

how to make json string by using php array?

This is the target jason string:
{"dpid": 272, "priority": 10, "match": {"nw_src": "192.168.1.1", "nw_dst": "192.168.1.2", "nw_proto": 1, "eth_type": 0x0800}, "actions":[{"type": "DROP"}]}
This is the php array that i made:
$rule = array(
"dpid" => 272,
"priority" => 10,
"match" => {"nw_src": "$_POST['src']", "nw_dst": "$_POST['dst']", "nw_proto": 1, "eth_type": 0x0800},
"actions"=> [{"type": "DROP"}],
);
i am trying to turn this array into the json string above, using:
$data_string=json_encode( $rule );
but it doesnt work :(
i know the array is really non-sense, i am really new to php. Could somebody help me?
Your array should be:
$rule = array(
"dpid" => 272,
"priority" => 10,
"match" => array(
"nw_src" => $_POST['src'],
"nw_dst" => $_POST['dst'],
"nw_proto" => 1,
"eth_type" => 0x0800
),
"actions"=> array(array("type" => "DROP")),
);
After that json_encode function will do all the work for you:
$data_string = json_encode($rule);

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']
)
)
);

Categories