我正在尝试将此结果数组转换为JSON:
[{"RouteId":1,"TrackerRouteList":
[{"TrackerId":7,"CoordinateList":
[{"Latitude":"21.115957","Longitude":"-86.838120"},
{"Latitude":"21.11558","Longitude":"-86.838127"}]
}]
},
{"RouteId":2,"TrackerRouteList":
[{"TrackerId":8,"CoordinateList":
{"Latitude":"21.110843","Longitude":"-86.840906"},
{"Latitude":"21.110757","Longitude":"-86.841915"}]
}]
},
{"RouteId":3,"TrackerRouteList":
[{"TrackerId":9,"CoordinateList":
[{"Latitude":"21.111201","Longitude":"-86.842218"},
{"Latitude":"21.110757","Longitude":"-86.841915"}]
}]
}]
我正在使用此代码以最清晰的方式组织数据:
$Results = $SOAPIClient->LinesOnRoutes($num);
$Lat = '';
$Lon = '';
foreach($Results as $Route)
{
$Results->RouteId;
foreach($Route->TrackerRouteList as $unit)
{
$unit->TrackerId;
foreach($unit->CoordinateList as $Coordinates)
{
$Lat = $Coordinates->Latitude;
$Lon = $Coordinates->Longitude;
echo $Point = 'Unit:'.$unit->TrackerId.'[ ' .$Coordinates->Latitude.','.$Coordinates->Longitude.' ]';
}
}
}
结果如下:
Unit:7[ 21.115957,-86.838120 ]
Unit:7[ 21.11558,-86.838127 ]
Unit:8[ 21.110843,-86.840906 ]
Unit:8[ 21.110757,-86.841915 ]
Unit:9[ 21.111201,-86.842218 ]
Unit:9[ 21.110757,-86.841915 ]
如何将结果转换或分组到此?
Unit:7 [ [ 21.115957,-86.838120 ], [ 21.11558, -86.838127 ] ];
Unit:8 [ [ 21.110843,-86.840906 ], [ 21.110757, -86.841915 ] ];
Unit:9 [ [ 21.111201,-86.842218 ], [ 21.110757, -86.841915 ] ];
答案 0 :(得分:0)
使用以下代码获得预期结果:
foreach($Results as $Route)
{
foreach($Route->TrackerRouteList as $unit)
{
echo 'Unit:'.$unit->TrackerId.' [';
$aux = '';
foreach($unit->CoordinateList as $Coordinates)
{
echo $Point=$aux.'[ ' .$Coordinates->Latitude.','.$Coordinates->Longitude.' ]';
$aux=',';
}
echo "];\n";
}
}
此代码正确地将字符串格式化为JSON数据:
foreach($Results as $Route)
{
$arrayJson = array();
$i = 0;
foreach($Route->TrackerRouteList as $unit)
{
$arrayJson[$i]['Unit'] = $unit->TrackerId;
foreach($unit->CoordinateList as $Coordinates)
{
$arrayJson[$i]['Coordinates'][] = array($Coordinates->Latitude, $Coordinates->Longitude);
}
$i++;
}
echo json_encode($arrayJson);
}