[英]Assigning PHP variable to PHP array
I want to assign some php to a javascript variable like: 我想将一些php分配给javascript变量,例如:
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
but ends up with: 1 (instead of 2000). 但结果为:1(而不是2000)。
Here's my troubleshooting: 这是我的疑难解答:
I have an array in a php class: 我在php类中有一个数组:
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
),
I've tried to assign through a couple of variables to find the problem with no luck: 我尝试通过几个变量进行赋值,但发现运气不好:
var goldLevel = <?php $user->getResource($data -> id, "goldLevel") ?>;
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
var goldPrice1 = <?php echo ResourceArray::$goldLevel[1]?>;
This writes: 写道:
var goldLevel = 1;
var goldPrice = 1;
var goldPrice1 = 2000;
Finally I tried to assign a php variable to put in: 最后,我尝试分配一个php变量以放入:
PHP: $goldLevel1 = $user->getResource($data->id, "goldLevel");
$goldLevel2 = 1;
js: var goldPrice2 = <?php echo ResourceArray::$goldLevel[$goldLevel1]?>;
var goldPrice3 = <?php echo ResourceArray::$goldLevel[$goldLevel2]?>;
This ends up like: 最终像这样:
var goldPrice2 = ;
var goldPrice3 = 2000;
When I echo $goldLevel1 and $goldLevel2, it shows 1 and 1. 当我回显$ goldLevel1和$ goldLevel2时,它显示1和1。
Trying this works fine with me: 试试这个对我来说很好:
<html><body>
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
);
}
// set gold price to second entry of goldLevel array
$goldPrice = ResourceArray::$goldLevel[1];
// check to make sure we have a valid number
if (!is_numeric($goldPrice) || $goldPrice < 1)
$goldPrice = 0;
// this outputs 2000
echo $goldPrice;
?>
<script>
var goldPrice = <?php echo $goldPrice; ?>;
alert(goldPrice);
</script>
</body></html>
Try using json_encode() 尝试使用json_encode()
Documentation for json_encode json_encode的文档
Use it like this 这样使用
var goldPrice = <?php echo json_encode(array(0, 2000, 10000))?>;
Just replace the array for the dynamically created one. 只需将数组替换为动态创建的数组即可。
First of all create a variable of json 首先创建一个json变量
var jsonO = <?php echo json_encode(array(0, 2000, 10000))?>;
this will be a json string, convert it to javascript array 这将是一个json字符串,将其转换为javascript数组
var goldPrice = $.map(jsonO, function(el) { return el; })
then use goldPrice array. 然后使用goldPrice数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.