首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从php array_push和循环创建javascript文件

从php array_push和循环创建javascript文件
EN

Stack Overflow用户
提问于 2021-04-20 15:49:04
回答 1查看 34关注 0票数 0

我在php中生成了如下数组:

代码语言:javascript
复制
array_push($json, (object)[
  'location_lat' => $spot_lat,
  'location_lng' => $spot_lng,
  'cat' => $spot_category,
  'additional' => $spot_additional
]);

这个代码在我的“while”循环中。在我的功能结束时,我要做的是:

代码语言:javascript
复制
  $fp = fopen('my-path/spots.js', 'w');
  $addressPoints = json_encode($json);
  fwrite($fp, $addressPoints);
  fclose($fp);

所有的工作都很好,我得到了一个很好的spots.js文件,如下所示:

代码语言:javascript
复制
[{"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"]}]

但问题是,我不知道如何将这个数组设置为变量?我需要生成这样的.js文件:

代码语言:javascript
复制
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"]}]

解决办法可能很简单,但我做不到。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-20 16:08:48

$addressPoints是一个字符串。因此,您可以简单地向其添加所需的var声明:

代码语言:javascript
复制
$addressPoints = 'var myCustomVariable = ' . json_encode($json);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67182224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档