CaitlinHavener
CaitlinHavener

Reputation: 1418

Create a Javascript array from a PHP array

I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.

PHP:

$simpleArray= [];   
$childProducts = Mage::getModel('catalog/product_type_configurable')
    ->getUsedProducts(null,$_product);   
foreach($childProducts as $child) { //cycle through simple products to find applicable
    $simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
    var_dump ($simpleArray);
}

Javascript:

var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{   
    console.log(simpleArray);
    //which color id is selected 
    var colorSelected = $j("#attribute92 option:selected").val();
    console.log('Value of color selected is ' + colorSelected);
    $j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}

Edit: I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.

Upvotes: 2

Views: 234

Answers (3)

km6zla
km6zla

Reputation: 4907

try a for in loop.

for( item in data ) {
    console.log(data[item]);
}

this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.

Edit thanks to comments changed data.item to data[item]

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71422

The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:

var simpleArray = <?= $simpleArrayJson ?>;

This will output a javascript object literal.

Upvotes: 3

Orangepill
Orangepill

Reputation: 24655

Remove from the php.

$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);

here you are converting the php array into a json string.

Change in the javascript

var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;

Here you are just outputting the sting. previously you where doing this

var simpleArray = <?=(array) json_decode($simpleArrayJson)?>

which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:

var simpleArray = Array; 

Upvotes: 0

Related Questions