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.