0

我正在尝试将此结果数组转换为 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 ] ];
4

1 回答 1

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);
}
于 2013-06-16T02:00:23.157 回答