0

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

enter image description here

4
  • What's IDs and data? Your simpleArray[i][colorSelected] is right, provided i (taken from IDs.length) is a value in the first dimension. Commented May 23, 2013 at 20:20
  • "need to access"? Why not use the original array? $simpleArray[5][7]. json is a data encapsulation/transport format. it's nothing something you should EVER be attempting to "access". Commented May 23, 2013 at 20:26
  • I need to access the php array within the javascript because it's dynamic on the page. I just took a clip of this code. Before it is a ajax request, hence the data, but it shouldn't be applicable to this issue. Commented May 23, 2013 at 20:30
  • 2
    Your object doesn't have keys at 0 1 and 2, you'll get an error on simpleArray[i][colorSelected] because i first equals 0. Commented May 23, 2013 at 20:34

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Object keys are toString()'d anyway, so parseInt or no-parseInt should make a difference (jsfiddle.net/SEaFy).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.