I have the following which assigns the values I need to an array in php
我有以下代码,它将我需要的值分配给php中的数组
$resultsAr[$row['stop_name']][$row['route_long_name']][] = $row['arrival_time'];
However when I convert this to JSON it does not have any keys.
但是,当我将它转换为JSON时,它没有任何键。
echo json_encode($resultsAr);
e.g.
如。
{
Stop1: {
Destination1: [
"11:13",
"11:25"
],
Destination2: [
"11:15",
"11:27"
],
Destination3: [
"11:14",
"11:23",
"11:26"
]
},
They keys are actually the values. How can I assign key names to the array?
它们的键实际上是值。如何为数组分配键名?
Edited: the required JSON output would be keys with values:
已编辑:所需的JSON输出为键值:
[Stops => all stops] [destinations => destinations] [times => arrival times]
2 个解决方案
#1
0
You must be set key for array when you want to encode array to json
要将数组编码为json,必须为数组设置键
Example:
例子:
$i=0;
foreach ($rows as $row) {
$resultsAr[$row['stop_name']][$row['route_long_name']][$i] = $row['arrival_time'];
$i++;
}
#2
1
Can you try:
你可以尝试:
$obj = new stdClass();
$obj->name = "Stop1";
$obj->data = array(
array("Destination1",array("11:13","11:25")),
array("Destination2",array("11:13","11:25")),
array("Destination3",array("11:13","11:25")),
);
echo json_encode($obj);
On a side note Only numeric items can appear without quotation. json.org
在边注中,只有数字项可以不带引号地出现。json.org
Also to explain stdclass - What is stdClass in PHP?
还要解释stdclass——PHP中的stdclass是什么?
#1
0
You must be set key for array when you want to encode array to json
要将数组编码为json,必须为数组设置键
Example:
例子:
$i=0;
foreach ($rows as $row) {
$resultsAr[$row['stop_name']][$row['route_long_name']][$i] = $row['arrival_time'];
$i++;
}
#2
1
Can you try:
你可以尝试:
$obj = new stdClass();
$obj->name = "Stop1";
$obj->data = array(
array("Destination1",array("11:13","11:25")),
array("Destination2",array("11:13","11:25")),
array("Destination3",array("11:13","11:25")),
);
echo json_encode($obj);
On a side note Only numeric items can appear without quotation. json.org
在边注中,只有数字项可以不带引号地出现。json.org
Also to explain stdclass - What is stdClass in PHP?
还要解释stdclass——PHP中的stdclass是什么?