Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting PHP array into Javascript array

I have an array like this:

Array
(
[0] => Array
    (
        [id] => 9826
        [tag] => "php"
    )

[1] => Array
    (
        [id] => 9680            
        [tag] => "perl"
    )

)

I want to pass this to a javascript variable that looks like this:

var availableTags = [
        "ActionScript",
        "AppleScript",
        "Asp",
        "BASIC",
        "C",
        "C++",
        "Clojure",
        "COBOL",
        "ColdFusion",
        "Erlang",
        "Fortran",
        "Groovy",
        "Haskell",
        "Java",
        "JavaScript",
        "Lisp",
        "Perl",
        "PHP",
        "Python",
        "Ruby",
        "Scala",
        "Scheme"
    ];

I have gotten this far:

var availableTags = [
        <?php
                        foreach($Tags as $tag){
                              echo $tag['tag'];
                        }
                    ?>
    ];

the problem I have is adding the double quotes around each tag and inserting a comma after each apart from the last.

I'm not sure of how to best do that?

like image 560
iamjonesy Avatar asked Apr 11 '26 22:04

iamjonesy


1 Answers

Save yourself some lines of code:

var availableTags = <?php
function get_tag($value) {
    return $value['tag'];
}
echo json_encode(array_map("get_tag", $Tags));
?>
like image 64
thetaiko Avatar answered Apr 14 '26 11:04

thetaiko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!