Adding php loop data to js array

arrays, foreach, javascript, javascript-objects, php

Solution

There is a more better and clean way, use `json_encode` PHP

<?php
  $data = array();
  foreach( $this->products as $product ) {
    $data[] = array(
      "id"    =>  $product->virtuemart_product_id,
      "name"  =>  $product->product_name
    );
  }
?>

HTML

<script type=text/javascript>
  var product = <?php echo json_encode( $data ) ?>;
</script>

You can also use

var product = <?php echo json_encode( $product ) ?>;

So when you want to access the `product` with javascript, your code will be

<script type="text/javascript">
  for( i in product ) {
    console.log( product[i] );
  }
</script>

Problem

I have a php loop that loops through products and their data: ``` <?php foreach ($this->products as $product) { ?> <script type=text/javascript> product = { id: $product->virtuemart_product_id, name: $product->product_name }; </script> <?php } ?> ``` The data contains information about the product un the $product like so: - $product->virtuemart_product_id - $product->product_name Is it possible to add the data to a existing javascript array or object in each of the loops? Basically it will add the data of the loop to the javascript array or product. Any help would be appreciated :)

Original source