-1

I have a PHP var with a multidimensional array. I want to access that var in a javascript function and iterate over an element of the array (belongs_to). How can I do this?

This is the php var:

<?php

    $q1 =[1=>['old_id'=>1,'belongs_to'=>null],
          2=>['old_id'=>2,'belongs_to'=>null],
          3=>['old_id'=>3,'belongs_to'=>null],
          4=>['old_id'=>4,'belongs_to'=>null],
          5=>['old_id'=>5,'belongs_to'=>null],
          6=>['old_id'=>6,'belongs_to'=>null];
          1030=>['id'=>1030,'belongs_to'=>1],
          1031=>['old_id'=>1031,'belongs_to'=>1],
          1032=>['old_id'=>1032,'belongs_to'=>2],
          1033=>['old_id'=>1033,'belongs_to'=>2];   
?>

2 Answers2

0

Php runs on server, javascript runs on browser. Because of this reason you can not reach the php variable from the javascript file.

The most easiest way to access your array is AJAX. You can write an ajax call from the script and server returns the json encoded php array.

After that you can use your php array in your script with decoding json to javascript object. To decoding encoded json to javascript array parseJSON() function.

oguzhancerit
  • 1,436
  • 1
  • 16
  • 27
0

You have 2 ways to do this.

The most straightforward would be to output that array in some format (preferably JSON) as the value of a hidden <input> in your HTML:

<?php
   $q1 = [ /* stuff here */ ];
   $json = json_encode($q1);
   echo '<input id="arrayData" value="' . htmlentities($json) . '"/>';

You can then read the value of that input, parse it, and then use it from the JavaScript side:

const q1 = JSON.parse(document.querySelector('#arrayData').value);

Note the id of the input is the same as the selector in querySelector (though it can be any value).

The other method, which is cleaner but involves more work, is to create a new PHP endpoint that would return the array as JSON, then use one of the many AJAX methods to read it.

A code example would be a bit long, but there are plenty of examples of it out there.

samanime
  • 25,408
  • 15
  • 90
  • 139