简体   繁体   中英

Push values from Smarty PHP array to JavaScript array

I am looping an array which has some data coming from db. I want to save those values in one array using JavaScript. I want the array to maintain its content, so when i use it inside another script tag it still has its values. I am really stucked.

{foreach from=$car_owner item=car_pos}
    <script type="text/javascript">
        arr = [
                [{$car_pos['longitude']}, {$car_pos['latitude']}]
              ];
        console.log(arr);
    </script>
{/foreach}

The code i wrote saves the values in two different arrays(because the $car_owner array has two indexes from db) which i dont want it to happen. And when i output the array in an other script tag it shows me just the last index that has been saved in the array and not the whole content.

** SOLVED **

The vector declaration should be outside the Smarty loop!

  1. I had to declare a vector instead.
  2. Push each element inside the Smarty loop.
arrayPos.push([{$car_pos['longitude']}, {$car_pos['latitude']}]);

try this:

<script type="text/javascript">
  let arr=[];
</script>
{foreach from=$car_owner item=car_pos}
<script type="text/javascript">
    arr.push([{$car_pos['longitude']}, {$car_pos['latitude']}]);
</script>
{/foreach}
<script type="text/javascript">
  console.log(arr);
</script>

first: declare an array variable, don't declared a variable in looping because your code will be error :

<script type="text/javascript">
  let arr=[];
</script>

second: put your lopping code and then put loop value in your array variable your declared before:

{foreach from=$car_owner item=car_pos}
<script type="text/javascript">
    arr.push([{$car_pos['longitude']}, {$car_pos['latitude']}]);
</script>
{/foreach}

(optional) last: if you want to show your all array variable value, you can add console.log below of loop, don't put console.log in looping, if you put your console.log in loop then you only see the last of loop value:

<script type="text/javascript">
  console.log(arr);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM