我有从php生成的json数组。但是格式不是我想要的。我有相关的问题,但不是我想要的格式。请在下面查看我做了什么并尝试过vs我想要的
//////////////
$data variable array
///////////////
Array
(
[0] => Array
(
[id] => 2
[start_date] => 2018-05-17 08:40
[end_date] => 2018-05-17 09:00
)
[1] => Array
(
[id] => 3
[start_date] => 2018-05-17 08:40
[end_date] => 2018-05-17 09:00
)
)
这就是我所做的
$array[] = $data;
echo json_encode($array);
输出
[
{"id":2,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"},
{"id":3,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"}
]
这是我尝试过的
$array["data"] = $data;
echo json_encode($array);
输出
{"data":
{"id":2,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"},
{"id":3,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"}
}
我想要的输出
{
"data": [
{"id":2,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"},
{"id":3,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"}
]
}
答案 0 :(得分:1)
我没有使用<React.Fragment>
<ul>{arr.map(item => <MyAppChild key={item.Name} Name={item.Name} Roughness={item.Roughness} Thickness={item.Thickness} />)}</ul>;
<ul><ProductNameSave onChance ={fields => this.handleChange(fields)}/></ul>;
</React.Fragment>
,而是将“数据”放入一个数组,然后将另一个数据放入$array["data"]
。
$data
上面的代码将输出如下内容:
$array = array("data" => $data);
$enData = json_encode($array); //encoding array to json
$deData = json_decode($enData, true); //decoding array
print_r($deData);
,如果您这样做:
Array
(
[data] => Array
(
[id] => 3
[start_date] => 2018-05-17 08:40
[end_date] => 2018-05-17 09:00
)
)
答案 1 :(得分:0)
您需要先将$data
设置为数组。
例如:
$data[] = ["id" => 2, "start_date" => "2018-05-17 08:40", "end_date" => "2018-05-17 09:00"];
$array["data"] = $data;
echo json_encode($array);
哪个返回:
{
"data":[
{"id":2,"start_date":"2018-05-17 08:40","end_date":"2018-05-17 09:00"}
]
}
答案 2 :(得分:0)
您必须先构建一个数组,然后构建一个对象。见下文
$array = [
[
"id" => 2,
"start_date" => "2018-05-17 08:40",
"end_date" => "2018-05-17 09:00"
],
[
"id" => 3,
"start_date" => "2018-05-17 08:40",
"end_date" => "2018-05-17 09:00"
]
];
$data["data"] = $array;
echo json_encode($data);
答案 3 :(得分:0)
似乎您是从sql输出循环中获取$ data的:
$array = ["data"=>[]];// initialize $array outside your loop
while($data = mysqli_fetch_assoc($result)){
$array['data'][] = $data; // push $data into $array['data']
}
echo json_encode($array);