views:

111

answers:

4

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?

+5  A: 
var availableTags = [
<?php
  $tag_strings = array();
  foreach($Tags as $tag){
        $tag_strings[] = '"'.$tag['tag'].'"';
  }
  echo implode(",", $tag_strings);
  ?>
];
Mikee
@Mikee beat me to it :)
Andrew Sledge
Thanks worked a treat!
iamjonesy
+2  A: 
var availableTags = [
        <?php
                        foreach($Tags as $tag){
                              echo '"'.$tag['tag'].'",';
                        }
                    ?>
    ];
Phill Pafford
The extra comma will break IE.
Blair McMillan
hmm jQuery handles this, but after testing you guys are right. ugh, learning
Phill Pafford
+7  A: 

Save yourself some lines of code:

var availableTags = <?php
function get_tag($value) {
    return $value['tag'];
}
echo json_encode(array_map("get_tag", $Tags));
?>
thetaiko
+1, this is exactly what `json_encode` is for. But it's not quite right, you need to make an array in PHP which is just 'tag', and `json_encode` that.
Skilldrick
+1 for json_encode.
Rocket
@Skilldrick - indeed you are correct. Code changed appropriately.
thetaiko
Use a lambda instead of a named function. `array_map(function($this){ /**/ }, $Tags);` Other than that, +1
BBonifield
@BBonifield - would have except that a lot of people not yet using >= PHP 5.3.
thetaiko
A: 
<?php 
$arr = array(
0 => array("id" => 9826, "tag" => "php"),

1 => array("id" => 9680, "tag" => "perl")
);

$my_array;

foreach($arr as $key=>$val) {
   $my_array[] = $arr[$key]['tag'];
}

$availableTags = json_encode($my_array);
echo $availableTags;
?>
Q_the_dreadlocked_ninja