2

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 Answers 5

10

Save yourself some lines of code:

var availableTags = <?php
function get_tag($value) {
    return $value['tag'];
}
echo json_encode(array_map("get_tag", $Tags));
?>
Sign up to request clarification or add additional context in comments.

4 Comments

+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 - indeed you are correct. Code changed appropriately.
Use a lambda instead of a named function. array_map(function($this){ /**/ }, $Tags); Other than that, +1
@BBonifield - would have except that a lot of people not yet using >= PHP 5.3.
6
var availableTags = [
<?php
  $tag_strings = array();
  foreach($Tags as $tag){
        $tag_strings[] = '"'.$tag['tag'].'"';
  }
  echo implode(",", $tag_strings);
  ?>
];

Comments

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

2 Comments

The extra comma will break IE.
hmm jQuery handles this, but after testing you guys are right. ugh, learning
1

Try:

var availableTags = <?php
echo json_encode(array_map(create_function('$v','return $v[\'tag\'];'), $Tags));
?>;

Comments

0
<?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;
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.