0

I'm able to print the following item name values using the following in PHP.

I'm stuck trying to take a PHP array, and use it in JavaScript.

foreach($orderArray[0]->items as $data){
    echo $data->name; echo "<br>";
    echo $data->productId; echo "<br>";
}

How would I take this array, and make this an array in JavaScript and print the values of name and productId for each item ?

I'm new to JavaScript and know I can convert the array as below, but not sure how to get the values into a JavaScript's Multidimensional Associative array, where I can print the values in JavaScript.

var array1 = '<?php echo json_encode($orderArray); ?>';
Littm
  • 4,923
  • 4
  • 30
  • 38
  • 1
    Leave off the quotes (`' '`) and your echoed code will be an object literal that can be used right away. Otherwise you would need to use `JSON.parse()` to decode the echoed string – Patrick Evans May 31 '20 at 01:38
  • ^ which may not be the worst idea if the JSON is rather big. JSON is a way simpler format than JS literals. But that's optimization and Off Topic. – Thomas May 31 '20 at 01:40

1 Answers1

0

Your code is all correct and here after you can access elements in an array similar to that of the PHP array as

<?php
$data = [1 => [1,2,3],2,3,4,5,6];
?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p>
<script>
var a = <?php echo json_encode($data);?>;
document.write(a[1]);
</script>
</p>
</body>
</html>

Output

1,2,3

And you can also access the elements in the for loop similar to that of the PHP array.

Kunal Raut
  • 2,495
  • 2
  • 9
  • 25