Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding php loop data to js array

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

like image 355
Sebastian Opperman Avatar asked Jun 08 '26 13:06

Sebastian Opperman


2 Answers

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>
like image 61
bystwn22 Avatar answered Jun 11 '26 04:06

bystwn22


You can use json using the php function json_encode:

<script type='text/javascript'>
<?php
    $products = $this->products;
    $js_array = json_encode($products);
    echo "var products = ". $js_array . ";\n";
?>
</script>

Another way to do the same thing:

<script type="text/javascript">
    var products= <?php echo json_encode($products); ?>;
    for(var i=0;i<n;i++)
    {
        alert(products[i]);
    }
</script>
like image 42
Joshua Kissoon Avatar answered Jun 11 '26 04:06

Joshua Kissoon