0

I have array generated in php like this:

array_push($json, (object)[
  'location_lat' => $spot_lat,
  'location_lng' => $spot_lng,
  'cat' => $spot_category,
  'additional' => $spot_additional
]);

This code is in mine 'while' loop. And the end of my function I'm doing this:

  $fp = fopen('my-path/spots.js', 'w');
  $addressPoints = json_encode($json);
  fwrite($fp, $addressPoints);
  fclose($fp);

All working well, I'm getting fine spots.js file looking like this:

[{"location_lat":"49.6149366","location_lng":"22.2754669","cat":"na-dziko","additional":["is_verified","paid","bike","fishing","pitch","shop","river","lake","forest","buildings","playground","sanitary","wifi","barbecue","kitchen","year","electricity"]},{"location_lat":"49.4257138","location_lng":"20.4740524","cat":"kempingi-i-pola-namiotowe","additional":["paid","bike","trails","river","forest","mountains","sanitary","barbecue","kitchen","electricity"]},{"location_lat":"44.52625","location_lng":"1.71944","cat":"kempingi-i-pola-namiotowe","additional":["paid","bike","pool","fishing","water_sport","trails","climber","6","Array","shop","river","forest","mountains","4","Array","sanitary","wifi","kitchen","restaurant","electricity","5","Array"]}]

But the problem is i dont know how to set this array as variable? I need to generate my .js file like this:

var myCustomVariable = [{"location_lat":"49.6149366","location_lng":"22.2754669","cat":"na-dziko","additional":["is_verified","paid","bike","fishing","pitch","shop","river","lake","forest","buildings","playground","sanitary","wifi","barbecue","kitchen","year","electricity"]},{"location_lat":"49.4257138","location_lng":"20.4740524","cat":"kempingi-i-pola-namiotowe","additional":["paid","bike","trails","river","forest","mountains","sanitary","barbecue","kitchen","electricity"]},{"location_lat":"44.52625","location_lng":"1.71944","cat":"kempingi-i-pola-namiotowe","additional":["paid","bike","pool","fishing","water_sport","trails","climber","6","Array","shop","river","forest","mountains","4","Array","sanitary","wifi","kitchen","restaurant","electricity","5","Array"]}]

The solution is probably very simple, but I can't do it.

1
  • Concatenate the strings? Just add var myCustomVariable = before the JSON encoded array. Commented Apr 20, 2021 at 15:58

1 Answer 1

2

$addressPoints is a string. So you can simply add the desired var declaration to it:

$addressPoints = 'var myCustomVariable = ' . json_encode($json);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, i know that's very simple :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.