简体   繁体   中英

Accessing Matrix Array Value in Json_encoded Array

I have a php array that I assigned to a javascript variable with json_encode. The php array is numerical not associative.

Example: simpleArray[5][7]=1.50. I need to be able to access the 1.50 after the array has been json_encoded based on the index values.

PHP:

$simpleArray= [];   

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);//see the picture of me below
    var colorSelected = $j("#attribute92 option:selected").val(); //integer value

    $j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}

Console.log(simpleArray):

在此处输入图片说明

Here you are likely trying to access values that don't exist in your object:

simpleArray[i][colorSelected]

Based on your for loop definition, you can have i values of 0, 1, 2 which don't exist in the object shown (which has properties at keys: 3,4,5). Also your for loop has no relation at all to the number of items in your object, which I am not sure is intended.

Also, colorSelected derives it's value from a call to val() which returns a string you you probably want to change the line where it is defined to:

var colorSelected = parseInt($j("#attribute92 option:selected").val());

This will make it an integer value.

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