Pass json encoded array to javascript function

I have to pass a PHP JSON array into a JavaScript function's on click event.

Before JSON encode PHP array structure:

Array
[
    [group_id] => 307378872724184
    [cir_id] => 221
]

After JSON encode array structure:

{"group_id":"307378872724184","cir_id":"221"}

The PHP JSON array looks like:

if[!empty[$cirGrpArr]]

   $jsonGrpArr = json_encode[$cirGrpArr];

I need to pass the same into a javascript on click function like below:


  • Using json_encode[] function to retrieve the array elements
    var passedArray = ;
  • Example:

    // Access the array elements

    var passedArray = 

        ;

    // Display the array elements

    for[var i = 0; i < passedArray.length; i++]{

        document.write[passedArray[i]];

    }

    Output:

    GeeksforGeeks

    Method 2: Using PHP implode[] function: The implode[] is used to join the elements of an array. The implode[] function is the alias of join[] function and works exactly same as that of join[] function.
    The implode[] function is used to build a string that becomes an array literal in JavaScript. So, if we have an array in PHP, we can pass it to JavaScript as follows:

    var passedArray = ;
    

    Example:

    // Using PHP implode[] function

    var passedArray = 

        ;

    // Printing the passed array elements

    document.write[passedArray];

    Output:

    Car, Bike, Boat

    PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


    Chủ Đề