omkara
omkara

Reputation: 982

How to change json_encode API format laravel?

code:

$prop_map = DB::table('jk_property_map_jpm')->select('jpm_location','jpm_longitude','jpm_latitude')->where('jpm_location','like','%'.$par2.'%')->get();
foreach($prop_map as $k)
{
    $array = array(
                    $k->jpm_location,
                    $k->jpm_latitude,
                    $k->jpm_longitude
                    );
    $data['map'] = json_encode($array);
    echo $data['map'];
}

API:

[
  "California Frazier Park 93222 15501 Nesthorn Way",
  "34.852633",
  "-119.149963"
][
  "Oakhurst,Gold Country,California,United States",
  "37.3392607",
  "-119.7114921"
][
  "Club de Golf Fonatur, San Jos\u00c3\u00a9 del Cabo, Baja California Sur, Mexico",
  "23.0522956",
  "-109.6987974"
]

In this code I am simply used json_encode to create an API and here I am getting unexpected output as I mention above. I want data as mention below:

[   
    [
      "California Frazier Park 93222 15501 Nesthorn Way",
      "34.852633",
      "-119.149963"
    ],
    [
      "Oakhurst,Gold Country,California,United States",
      "37.3392607",
      "-119.7114921"
    ],
    [
      "Club de Golf Fonatur, San Jos\u00c3\u00a9 del Cabo, Baja California Sur, Mexico",
      "23.0522956",
      "-109.6987974"
    ]
]

So, How can I create like this? Please help me.

Thank You

Upvotes: 0

Views: 293

Answers (2)

Salim Djerbouh
Salim Djerbouh

Reputation: 11044

Use laravel collection mapping function to format and return your results instead of iterating via loop and echoing out

$prop_map = DB::table('jk_property_map_jpm')->select('jpm_location','jpm_longitude','jpm_latitude')->where('jpm_location','like','%'.$par2.'%')->get();
$prop_map = $prop_map->map(function ($k) {
        return [
            $k->jpm_location,
            $k->jpm_latitude,
            $k->jpm_longitude, // viva trailing commas
            ];
    });
return $prop_map; // laravel automatically serializes arrays to JSON

Upvotes: 1

Script47
Script47

Reputation: 14540

You can use array_values to turn your associative array into a numeric array.

Change,

$data['map'] = json_encode($v);

To,

$data['map'] = json_encode(array_values($v));

Upvotes: 1

Related Questions