7

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]]]; 
Teneff
  • 30,564
  • 13
  • 72
  • 103
user1029108
  • 87
  • 1
  • 2
  • 3

7 Answers7

22

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>
JohnP
  • 49,507
  • 13
  • 108
  • 140
  • 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. – ThiefMaster Dec 07 '11 at 10:17
  • You're absolutely right, missed the `var`. Added, thanks. – JohnP Dec 07 '11 at 10:22
  • Will the first one not treat `2011-12-02` as `1997` (because `-` is an arithmetic operator )? – KingCrunch Dec 07 '11 at 10:22
  • @KingCrunch yup, you're right. Should be quoted, thanks. – JohnP Dec 07 '11 at 10:25
  • Thank you for solution solve my problem – Kamran Sohail May 08 '18 at 06:46
4

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.

Matt Esch
  • 22,661
  • 8
  • 53
  • 51
2

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

Nenad
  • 3,438
  • 3
  • 28
  • 36
0

First of all: The arrays are not equivalent.

$array = array_map('array_values', $array);

this one is equivalent to the one you want to see as JS-array

$js = json_encode($array);

If you want to keep the keys of the associative (inner) arrays, just omit the first expression.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
0

If you want to do it in the smarty template, loop over your PHP array and output the javascript array elements, adding commas after every element except the last one.

s1 = [
{foreach from=$myArray item=item name=loop}
    [{$item['dt']}, {$item['number']}] {if $smarty.foreach.loop.last == false},{/if}
{/foreach}
]

As other said, though - encoding the array as JSON in PHP seems much cleaner and easier way to do that.

socha23
  • 10,171
  • 2
  • 28
  • 25
-1

first create a new javascript array:

var array = new array();

loop through the php array in your tpl and create the javascript array

foreach($phparray as $i => $ary) {
   echo "array[".$i."] = new array(".$ary['dt'].",".$ary['number'].");
}
clem
  • 3,345
  • 1
  • 22
  • 33
-4

there are many ways of doing it. I believe there are a lot of solution in the internet.

basically u just need to use for-loops to acheive it

i have already googled it for you. There

Houston
  • 69
  • 1
  • 1
  • 4
  • 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. – Alpants Jan 29 '22 at 20:34