简体   繁体   中英

Assigning PHP variable to PHP array

I want to assign some php to a javascript variable like:

var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;

but ends up with: 1 (instead of 2000).

Here's my troubleshooting:

I have an array in a php class:

<?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: $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.

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

Documentation for 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

 var jsonO = <?php echo json_encode(array(0, 2000, 10000))?>;

this will be a json string, convert it to javascript array

var goldPrice = $.map(jsonO, function(el) { return el; })

then use goldPrice array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM