Aaren San Aaren San - 29 days ago 9
JSON Question

Need some advise on PHP Session multidimensional array to Javascript

Good morning,

I'm just stuck within an issue which I can't follow even in the logical way. Maybe you can help me out by leading me to the right path.

I have a simple button which starts a simple function handing over an id. Right now I do have multiple buttons in a row with different ids

<a class="buttonControl btn btn-default btn-xs" href="javascript:play(999)" id="999">Play</a>
<a class="buttonControl btn btn-default btn-xs" href="javascript:play(888)" id="888">Play</a>

Next thing is I have a multidimensional array in php out of a php session.

$arr_a = array(
"999" => array(
"start" => "180",
"files" => array(
"mp3" => "http://example.com/999.mp3"
"888" => array(
"start" => "120",
"files" => array(
"mp3" => "http://example.com/888.mp3"

The JS function play(id) starts playing the audio file via the html5 audio object.

function play(x) {
...some code... get audio object ...

So am I right, when I describe the following:

  • convert the php array with json_encode [ ? ]

  • make JSON output available in js function [ ? ]

  • iterate through the json data until id match with key [ ? ]

  • get the 'mp3' value and hand it over to src audio object [ ? ]

  • play the file

So is this the right way from your point of view?

Thank you so much!

Best Regards

Answer Source

use json to change the context from php to javascript. The other steps are all right. But where do you struggle?

function play(x) {
  let jsonData = <?=json_encode($arr_a);?>;
  let mp3 = jsonData[x].files.mp3;
  document.querySelector('audio').src = mp3;