How to make a java script array from php array?

22,384

Solution 1

You'd have to loop through it to generate that array

<script>
   var arr = [];
   <?php foreach ($arr as $item) : ?>
   arr.push(['<?php echo $item['dt']?>', <?php echo $item['number']?>]);
   <?php endforeach; ?>
</script>

This will give you an array of arrays.

However, I would do it in another way. I'd just encode it with json and use it as an object

<script>
   var data = <?php echo json_encode($arr)?>;
   for (var x in data) {
      //data[x].dt;
      //data[x].number;
   }
</script>

Solution 2

I really dislike the idea of inline PHP all over the place. We don't inline JavaScript or CSS these days because it's bad practice i.e. difficult to maintain. We appreciate separation of concerns. If you need to pass data from your application (PHP or otherwise) to JavaScript variables on the client side then there are two good mechanisms you can use. Either get the result as JSON via AJAX, or simply render the variables on the client side in a single accessible location.

Your templating engine should really be able to register the data on the page for you. What you are essentially doing is rendering a script, so your script include mechanism should take an optional argument for registering php variables. If you are not using a templating engine and only need to inject the variables, I guess it would be acceptable to do something along the lines of.

<script type="text/javascript">
    var phpdata = <?php echo json_encode($phpdata)?>
</script>

Note that this is declaring a global. We are encouraged to avoid the usage of globals at all costs but I think it's a valid use case when sensibly chosen, such as if you register your own object in global scope as a sensible namespace, then refer to namespace.phpdata. Alternatively you simply wrap your JavaScript in an immediate function call and declare the variable in local scope.

function () {
    var phpdata = <?php echo json_encode($phpdata)?>

    ...
}();

But like I said, in my opinion I think it's better to get your templating engine to handle it, so you pass the PHP data you need for each javascript include, and a single php data object is generated from this data and included in your page.

Solution 3

You can use the php function json_encode to encode the array to json and then use it as an array like object in javascript

Share:
22,384
user1029108
Author by

user1029108

Updated on December 08, 2020

Comments

  • user1029108
    user1029108 over 3 years

    Iam using PHP,Smarty configuration.

    Iam getting an array in PHP and sent it to tpl.I would like to make a javascript array in tpl from that php array.

    PHP ARRAY

    Array
    (
        [0] => Array
            (
                [dt] => 2011-12-02
                [number] => 3
            )
    
        [1] => Array
            (
                [dt] => 2011-12-05
                [number] => 3
            )
    
        [2] => Array
            (
                [dt] => 2011-12-07
                [number] => 2
            )
    
    )
    

    and I want to get it as a java script array in tpl

    s1 = [[[2011-12-02, 3],[2011-12-05,3],[2011-12-07,2]]]; 
    
  • ThiefMaster
    ThiefMaster over 12 years
    Heh, i was going to downvote after reading the first half but then saw that you did suggest json_encode. But you really should use var x instead of just x. Global variables are bad. Even though it doesn't matter inside a script tag - but chances are good that the code might be inside a function eventually.
  • JohnP
    JohnP over 12 years
    You're absolutely right, missed the var. Added, thanks.
  • KingCrunch
    KingCrunch over 12 years
    Will the first one not treat 2011-12-02 as 1997 (because - is an arithmetic operator )?
  • JohnP
    JohnP over 12 years
    @KingCrunch yup, you're right. Should be quoted, thanks.
  • user1029108
    user1029108 over 12 years
    how to get that json encoded value from the variable $js to java script in tpl ? Please help me it is urgent..
  • KingCrunch
    KingCrunch over 12 years
    As usual: <script>var x = <?php echo $js; ?>;</script>
  • Kamran Sohail
    Kamran Sohail about 6 years
    Thank you for solution solve my problem
  • the_lone_note
    the_lone_note over 2 years
    We appreciate you trying to help, but pasting only links without content is against the rules and spirit of stack overflow. Pasting content directly into your answer is preferred (tho you can always add a link for more information). This is viewed as less condescending and guards against dead links in the future.