Facing special characters in json of laravel

Viewed 317

i don't know why special characters are coming , here is my code but first check out the image of special characters enter image description here

$output = [];

foreach ($vehicles as $key => $vehicle) 
{
    $center_lat = $lat;
    $center_lng = $lon;
    $lat=$vehicle->lat;
    $lng=$vehicle->lon;

    $vehicle->distance = haversineGreatCircleDistance($center_lat, $center_lng, $lat, $lng, 6371);
    

    $a_id= $vehicle->a_id;
    $a=DB::table('tbl')->where('id',$a_id)->get();

    $output [$key] = $vehicle;
    $result[] = array_merge((array)$output[$key],(array)$a);

}
return response()->json($result,201);

my output is like that

[
    {
        "id": 1,
         ......
        "distance": 3834.5607952869,
        "0": {"special character":
             [
                {
                    "id": 2,
                     .....
}
]

but i want my output in json format like that

 [
        {
            "id": 1,
             ......
            "distance": 3834.5607952869,
            "array_name": 
                    {
                        "id": 2,
                         .....
    }
    ]
1 Answers

You to make sure that you are converting the collection to an array, like so:

foreach ($vehicles as $key => $vehicle)
{
    $center_lat = $lat;
    $center_lng = $lon;
    $lat=$vehicle->lat;
    $lng=$vehicle->lon;

    $vehicle->distance = haversineGreatCircleDistance($center_lat, $center_lng, $lat, $lng, 6371);


    $a_id= $vehicle->a_id;
    $a=DB::table('tbl')->where('id',$a_id)->get()->toArray();

    $output [$key] = $vehicle;
    $result[] = array_merge((array)$output[$key], $a);

}
return response()->json($result,201);

The get() method for Eloquent ORM via DB returns a Collection object. So, when you try to convert a class object to an array, you get stray characters that will pop up that cause issues. Just make sure that you use the methods that they provide and it will solve all your issues.

See this documentation for more info: https://laravel.com/docs/7.x/collections#method-toarray

Related