I am receiving POST data from a form that is an array along with a few other fields. I need to take the array data only and pass it along in a post request of my own to a backend server as json.
The $_POST data looks like this:
Array (
[smsgte_submit] => Y
[alias] => Array (
[1] => Array (
[name] => mywife
[number] => 6135552001
[ssid] => 1 )
[2] => Array (
[name] => daughter
[number] => 6135553001
[ssid] => )
)
)
I only want to capture the alias entries and encode them in json.
I was successful in encoding the entire $_POST array into json with:
$data['jsonpost'] = json_encode($_POST);
which encoded the array as expected, however, I only want the alias array, so I tried the following:
$data['jsonpost'] = json_encode($_POST['alias']);
That, however doesn't work, it returns null to the server. Then I tried:
$data['jsonpost'] = json_encode(array_filter($_POST, 'alias'));
But that returned null.
Maybe I need to redesign my form, but in the end, I want a json array that looks like this:
{
"alias": {
"name":"mywife",
"number":"6135552001",
"ssid":"1"
},
"alias": {
"name":"daughter",
"number":"6135553001",
"ssid":"2"
}
}
It turns out that the following syntax should be correct:
$data['jsonpost'] = json_encode($_POST['alias']);
However, in order to get it to work, I had to split it as follows:
$jsonpost = json_encode($_POST['alias']);
$data['jsonpost'] = jsonpost;
I switched back and forth between the two options a few times, but only the second one works, at least with PHP 7.3.5.
Related
Okay, so I'm fairly new to PHP but it's enough like JS so I've been picking it up fairly quickly.
One issue I ran into the other day was getting the values from a JSON file.
My JSON file is 30,000 lines, but here's essentially what it looks like:
{
"congress": {
"Brown Sherrod": [{
"birthday": "1952-11-09"
}, {
"gender": "M"
}, {
"type": "sen"
}, {
"state": "OH"
}, {
"party": "Democrat"
}],
...
And anyway, it continues like that for another 29,000 + lines. My code to get the contents of the JSON file is this:
$data = json_decode(file_get_contents('path/to/file/convertcsv.json'), true);
It returns an array like this:
Array (
[0] => Array (
[birthday] => 1952-11-09
)
[1] => Array (
[gender] => M
)
[2] => Array (
[type] => sen
)
[3] => Array (
[state] => OH
)
[4] => Array (
[party] => Democrat
)
)
My issue I ran into is that I can't get the value of, say, ['birthday'] without using implode().
This works: $state = implode($data['congress'][$nameInput][3]);, but this does not: $state = $data['congress'][$nameInput][3];
Is there a reason why? I've read the docs on implode() (join array elements with string) and from what I gather from SO and the PHP docs this is how you get the value, but why? It makes no sense to have to convert the array to a string in order to get the value. In JavaScript to get the value from an array (or even a key-value) you just use the ['key'] or the [index] of the array, and it'll give you the value.
I feel like either I'm goofing on something major (not unlikely) or PHP is just weird -- probably the former. So, to reiterate my question (because I can ramble) am I making this too complex or is PHP just weird (and if so, is there a reason)?
Try below :-
$state = $data['congress'][$nameInput][3]['state']
I am using jQuery to convert form data to serialized form using:
var data = $('#frm').serialize();
In php I get this:
fiscalyear_id=4&category=Category+A&isgraph=on&Title=a&Value=a&Title=b&Value=b&category=Category+B&Title=c&Value=c&Title=d&Value=d&category=Category+C&Title=e&Value=e&Title=f&Value=f&data;=&csrf_check=9c288285b379701b27c3836091c00b04
And when I do:
parse_str($_POST['data'], $data);
pretty_print($data);
I get:
Array
(
[fiscalyear_id] => 4
[category] => Category C
[isgraph] => on
[Title] => f
[Value] => f
[data;] =>
[csrf_check] => 9c288285b379701b27c3836091c00b04
)
As can be seen, not all paramters are coming in array above. Does anyone have an idea what I am doing wrong ? Thanks for the help
parse_str parses the string in variable and you are getting it into array.
but duplicate array keys are not possible,
hence you are not getting all the values because they have the same key!
The following is a profile array printed using r_print:
Array
(
[0] => Array
(
[Title] => Profile
[Name] => Veritas
[NKey] => Key_1
[SKey] => Key_2
)
[1] => Array
(
[Title] => Access
[Admin] => True
[Banned] => False
[Public] => True
)
)
What I'm trying to do, is simply retrieve elements of that array.
IE,
$profile[] = ...; //GET_ARRAY
$user = $profile[0]['Name'];
$key_1 = $profile[0]['NKey'];
$key_2 = $profile[0]['SKey'];
$admin = $profile[1]['Admin'];
For some reason, the above code doesn't work, though logically it should work without a problem.
What IS returned, is just the character 'A' if I target anything within the array.
You are adding another level to your array by assigning the array to $profile[]. The brackets turn $profile into an array and then adds that array to it causing the extra level.
$profile[] = ...; //GET_ARRAY
should just be
$profile = ...; //GET_ARRAY
Figured out what I was looking for, thought PHP automatically formated arrays (string data) passed from another page. I solved my issue using serialize() & unserialize().
I have seen many posts on here about converting a multi dimensional array into a string but not the other way around so I have a question to ask. I have got the following string of data which is retrieved from a JQuery array via a post:
["enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk","http://www.gardengamesltd.co.uk/acatalog/contactus.html"],["enquiry#gardengames.com","http://www.gardengames.com/contact/"],["info#gardengamesandleisure.com","http://www.gardengamesandleisure.com/ContactUs.aspx"],["playtime#kentgardengameshire.com","http://www.kentgardengameshire.com/contact-us.html"],["sales#gardengamesuk.com","http://www.gardengamesuk.com/contact.php"],["team#gardenknightgames.com","http://www.gardenknightgames.com/contact/"],["ajax-loader#2x.gif","http://www.just-garden-games.co.uk/"]
What I am wanting to do is convert it into an array which looks like so:
Array
(
[0] => Array
(
[Email] => enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk
[FB] => http://www.gardengamesltd.co.uk/acatalog/contactus.html
)
[1] => Array
(
[Email] => enquiry#gardengames.com
[FB] => http://www.gardengames.com/contact/
)
[2] => Array
(
[Email] => info#aaeventhire.com
[FB] => http://www.aaeventhire.com/pricing/garden-games
)
)
I realize I could use $array = explode('","', $harvest_data); however this is only going to give me a single level array and ideally I am wanting to keep email, fb inside an inner array.
Has anyone got any ideas on how I can go about doing this?
Thanks.
As it is, your string is not valid JSON. Wrapping it in a pair of []'s would work in this case so if the input always has this form, this would work:
$json_string = '[' . $your_string . ']';
$your_array = json_decode($json_string);
However, it would be best to make sure that your front-end / javascript posts valid JSON to begin with.
Working example.
As see for the first and the third row all fields filled, for the second row some fields left blank.
Filled values with
$.post("__php_file.php", { 'number_of_input_row': number_of_input_row, 'date_day': date_day, 'date_month': date_month, 'date_year': date_year, 'currency': currency }, function(data, success) {
$('#currency_load1').html(data[0].FinalCurrencyRate);
$('#currency_load2').html(data[1].FinalCurrencyRate);
$('#currency_load3').html(data[2].FinalCurrencyRate);
}, "json");
send to php file, process and get such php array
Array
(
[0] => Array
(
[CurrencyAbbreviation] => AUD
[DateOfCurrencyRate] => 2013-07-11
[NumberOfInputRow] => 1
[FinalCurrencyRate] => 0.506
)
[2] => Array
(
[CurrencyAbbreviation] => CAD
[DateOfCurrencyRate] => 2013-07-25
[NumberOfInputRow] => 3
[FinalCurrencyRate] => 0.516
)
)
json array is this
{
"0":{"CurrencyAbbreviation":"AUD","DateOfCurrencyRate":"2013-07-11","NumberOfInputRow":"1","FinalCurrencyRate":"0.506"},
"2":{"CurrencyAbbreviation":"CAD","DateOfCurrencyRate":"2013-07-25","NumberOfInputRow":"3","FinalCurrencyRate":"0.516"}
}
So far all ok. But below is described problem
Get back results and display here
<div id="currency_load1"></div>
<div id="currency_load2"></div>
<div id="currency_load3"></div>
However get displayed only FinalCurrencyRate for AUD or [0] => Array.
Question is: what need to correct to get displayed also FinalCurrencyRate from [2] => Array? As you see in php such array presents, but is not passed to json...
If fill all fields for the second row, then get displayed all three arrays.
Update Tried this
$('#currency_load1').html(data[0].FinalCurrencyRate);
$('#currency_load2').html("test to check");
$('#currency_load3').html(data[2].FinalCurrencyRate);
And all works. As understand within jquery need to create condition like if FinalCurrencyRate is empty, then $('#currency_load2').html("0");? But why such json/jquery behavior?