我正在处理一些我存储在数组中的PHP输入,然后将其发布到需要JSON对象数组的API。发布下面的数据时,我总是收到错误消息。
请协助?
数组正在尝试发布
$children = ["child_name" => $cName , "child_dob" => $cDob];
dd($children);
转储后在浏览器中输出
array:2 [
"child_name" => array:5 [
0 => "Child 1"
1 => "mnmnmn"
2 => "mnmnmnm"
3 => "nbnbnb"
4 => "nbjhjgkgjhkg"
]
"child_dob" => array:5 [
0 => "2018-11-01"
1 => "2018-11-02"
2 => "2018-11-09"
3 => "2018-11-14"
4 => "2018-11-08"
]
]
需要从POST提取来自API的数据
{
"children":[
{"child_name":"abc","child_dob":"23-05-2015"}
]
}
答案 0 :(得分:1)
问题是您有一个名称和DOB数组,使用foreach()
可以很容易地通过遍历名称并添加相应的DOB来创建之后的输出...
$cName = ["Child 1", "cchild 2"];
$cDob = ["2018-01-01", "2018-02-02"];
$children = [];
foreach ( $cName as $key => $name ) {
$children[] = ["child_name" => $name , "child_dob" => $cDob[$key]];
}
echo json_encode([ "children" => $children], JSON_PRETTY_PRINT););
导致...
{
"children": [
{
"child_name": "Child 1",
"child_dob": "2018-01-01"
},
{
"child_name": "cchild 2",
"child_dob": "2018-02-02"
}
]
}
答案 1 :(得分:0)
Nigel Ren已经回答了这个问题。
但是对于那些想要以更加实用的PHP编程风格编写解决方案的人。我试图通过声明式而非命令式来解决这个问题。
<?php
$cName = array('Child 1', 'Child 2', 'Child 3');
$cDob = array('2018-11-01', '2018-11-02', '2018-11-03');
function mapChildNameToDob($childName, $dob)
{
return array(
'child_name' => $childName,
'child_dob' => $dob
);
}
$children['children'] = array_map("mapChildNameToDob", $cName, $cDob );
echo json_encode($children);
或者,如果您想使用匿名回调函数,则可以这样编写:
<?php
$cName = array('Child 1', 'Child 2', 'Child 3');
$cDob = array('2018-11-01', '2018-11-02', '2018-11-03');
$children['children'] = array_map(function($childName, $dob) {
return array(
'child_name' => $childName,
'child_dob' => $dob
);
}, $cName, $cDob );
echo json_encode($children);