0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you @Caddy DZ. I had a problem man i.e. I put $prop_map in $data like this $data['locations'] = $prop_map in my view file like {{ $location }} then it show " instead of double quots ` " ` So, How can I fix them?
Tha's because Blade echo directive {{ }} uses html_escape so you would have to trim the quotes in your php code before it reaches the view i.e trim($location, '"');
In case of jquery what will I do @Caddy DZ
In plain JS location.replace(/\"/g, "")
look I am fetching like var data = {{ $location }} and I am trying to replace " with " but nothing happen
|
1

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));

1 Comment

look my code once again I have changes something in my code @Script47

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.