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?

asked Oct 12, 2010 at 13:14

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));
?>
answered Oct 12, 2010 at 13:22
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);
 ?>
];
answered Oct 12, 2010 at 13:16

Comments

2
var availableTags = [
 <?php
 foreach($Tags as $tag){
 echo '"'.$tag['tag'].'",';
 }
 ?>
 ];
answered Oct 12, 2010 at 13:17

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));
?>;
Jérôme Verstrynge
59.9k97 gold badges297 silver badges469 bronze badges
answered Aug 13, 2011 at 18:31

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;
?>
answered Oct 12, 2010 at 13:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.