I am trying to encode an associative array in php
$data = array(
"firstName" => $_POST["firstName"],
"lastName" => $_POST["lastName"],
"email" => $_POST["email"],
"telephone" => $_POST["telephone"]
);
however the output is in string format and not in array format.
string(98) "{"firstName":"rob","lastName":"shelford","email":"some@domain.co.uk","telephone":"01245454545"}"
The output needs to have the square brackets so the receiving server can read the data correctly.
Is there another syntax for the $data array I need to use?
EDIT 1
The offical PHP documentation https://www.php.net/manual/en/function.json-encode.php
states that
echo "Normal: ", json_encode($a), "\n";
can be used to output
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
however when I try to use the "\n"
flag, I receive an error
EDIT 2
The entire data I wish to convert
$data = array(
"applicants" => array(
"firstName" => $_POST["firstName"],
"lastName" => $_POST["lastName"],
"email" => $_POST["email"],
"telephone" => $_POST["telephone"]
),
"buyerType" => $_POST["buyerType"],
"organisationId" => "xxxxxxxxxx",
"introducerId" => "0",
"introducerBranchId" => "0",
"introducerNegotiatorId" => "0",
);
EDIT 3 I have made it work by passing this into json_encode() :
$data = array(
"applicants"=> [
array(
"email"=> $_POST["email"],
"firstName"=> $_POST["firstName"],
"lastName"=> $_POST["lastName"],
"telephone"=> $_POST["telephone"]
)
],
"buyerType" => $_POST["buyerType"],
"organisationId" => "xxxxxxxxxx",
);
I have also removed the unnecessary lines in the above example
EDIT 4
The actual output I was expecting, and actually got, after implementing EDIT3
string(138) "{"applicants":[{"email":"some@domain.co.uk","firstName":"rob","lastName":"test","telephone":"01200000000"}],"buyerType":"Purchase"}"