我试图在php中编码一个关联数组。
$data = array(
"firstName" => $_POST["firstName"],
"lastName" => $_POST["lastName"],
"email" => $_POST["email"],
"telephone" => $_POST["telephone"]
);但是,输出是字符串格式,而不是数组格式。
string(98) "{"firstName":"rob","lastName":"shelford","email":"some@domain.co.uk","telephone":"01245454545"}"输出需要有方括号,以便接收服务器能够正确地读取数据。
对于我需要使用的$data数组,还有其他语法吗?
编辑1
官方的PHP文档https://www.php.net/manual/en/function.json-encode.php
国家
echo "Normal: ", json_encode($a), "\n";可用于输出
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]然而,当我尝试使用"\n"标志时,我会收到一个错误
编辑2
我希望转换的全部数据
$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",
);编辑3是通过将它传递到json_encode()中来实现的:
$data = array(
"applicants"=> [
array(
"email"=> $_POST["email"],
"firstName"=> $_POST["firstName"],
"lastName"=> $_POST["lastName"],
"telephone"=> $_POST["telephone"]
)
],
"buyerType" => $_POST["buyerType"],
"organisationId" => "xxxxxxxxxx",
);我还删除了上面示例中不必要的行。
编辑4
在实现EDIT3之后,我期望并实际得到的实际输出
string(138) "{"applicants":[{"email":"some@domain.co.uk","firstName":"rob","lastName":"test","telephone":"01200000000"}],"buyerType":"Purchase"}"发布于 2022-06-24 15:12:01
如果希望嵌套数组被方括号包围,只需将其放在php中的数组中即可。
$data['applicants'] = [$data['applicants']];
echo json_encode($data);FYI索引数组[1,2]将被编码到json列表[1,2],关联数组['x'=>1,'y'=>2]将被编码到json对象{"x":1,"y":1}。
https://stackoverflow.com/questions/72743894
复制相似问题