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
iamjonesy
25.2k42 gold badges145 silver badges206 bronze badges
5 Answers 5
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
thetaiko
7,8342 gold badges36 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Skilldrick
+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.thetaiko
@Skilldrick - indeed you are correct. Code changed appropriately.
BBonifield
Use a lambda instead of a named function.
array_map(function($this){ /**/ }, $Tags); Other than that, +1thetaiko
@BBonifield - would have except that a lot of people not yet using >= PHP 5.3.
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
Mikee
2,6032 gold badges19 silver badges16 bronze badges
Comments
var availableTags = [
<?php
foreach($Tags as $tag){
echo '"'.$tag['tag'].'",';
}
?>
];
answered Oct 12, 2010 at 13:17
Phill Pafford
85.6k92 gold badges268 silver badges385 bronze badges
2 Comments
Blair McMillan
The extra comma will break IE.
Phill Pafford
hmm jQuery handles this, but after testing you guys are right. ugh, learning
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
caiguanhao
4441 gold badge4 silver badges12 bronze badges
Comments
<?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
Q_Mlilo
1,7975 gold badges23 silver badges26 bronze badges
Comments
default