Jump to content

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!

Edited by Pain
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))

Edited by CroNiX

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);
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.