Jump to content

add php array to json array


Pain

Recommended Posts

Hello. I was wondering how can I add a php array to a js array containing json values.

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

I want to add this to the js array:

<?php $arr = array('red', 'green', 'blue'); ?>

I've tried doing this, but its definitely the wrong approach as it just sums everything up into one element "redgreenblue"

 
var availableTags = [
  "<?php foreach($arr as $row) { echo $row; } ?>",
  "AppleScript",
  "Asp",
  "BASIC",
....

Thanks for any kind of help!

Link to comment
https://forums.phpfreaks.com/topic/290543-add-php-array-to-json-array/
Share on other sites

Where is the js array stored? Somehow you'd have to get that into php-land, or vice-versa. Then just json_decode(js_array) and array_merge() it with your php array, or the other way around (json_encode(php_array) and concatenate the 2 js arrays using jsarray.concat(other_array))

Thanks for your effort. I have solved it by doing this:

 

 

 
<?php $php_cities_array = array('smth', 'smth2'); 
 
function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
 
function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}
 
$array = 'var availableTags = ' . js_array($php_cities_array) . ';';
 
?>
<script>
 
<?php echo $array; ?>
 
</script>

Something like this might work for you.

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

<?php
$arr = array('red', 'green', 'blue');
echo "var php_array = " . json_encode($arr) . ';';
?>

availableTags = availableTags.concat(php_array);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.