Leroy
Leroy

Reputation: 11

Parsing value of PHP array to jQuery

I am coding on a page which calculates a price dynamically when changing the input field :

<input type="number" id="amount" name="amount" type="number" value="0" min="1" max="6">

The calculation is base on a php array:

$plz[01] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );
$plz[02] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );
$plz[03] = array( 1=> 58, 2=> 43, 3=> 32, 4=> 26, 5=> 22, 6=> 19 );

Im trying to parse PHP code to my script and this works:

$("#amount").on('change',function() {
var sum = <?php echo $plz[01][6]; ?>;
}

But I need the value of the selected amount as key. Something like this:

$("#amount").on('change',function() {
var sum = <?php echo $plz[01] [$(this).val();] ?>;
}

Is there a way to do this? Thanks in advance.

Upvotes: 1

Views: 212

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337714

You could use json_encode in your PHP code to output the array in JSON to your JS code which you can then parse to an object.

var json = <?= json_encode($plz) ?>;
var arr = JSON.parse(json);

From there you can read the array as required:

$("#amount").on('change', function() {
    var sum = arr['01'][this.value - 1];
});

Working example

Note in the example above I included the JSON directly, but that is what should be output from PHP given your sample array.

Upvotes: 1

Related Questions