Search code examples
javascriptphpsmarty

save Smarty values dynamically in Multidimensional JavaScript array


I fetched data from the db and saved it in a smarty array. Now I want to save those values in a javascript array and i dont know the size of it.

{foreach from=$car_owner item=car_item}
    <tr>
        <td>
            <a href="#">
                <script>
                    var arrayPos = [
                        ['{$car_item['longitude']}', '{$car_item['latitude']}']]
                    ];
                </script>
                {$car_item['carName']}
            </a>
        </td>
    </tr>
{/foreach}

The array is only saving one value for the longitude and one for the latitude despite that i have more than one value for each one. Im sure i need to loop it, but as i said i dont know the size of what i should loop because the $car_owner array contains data fetched from the db. An help would be appreciated. Regards


Solution

  • You can do this with two loops.

    <script>
    var arrayPos = [
    {foreach from=$car_owner item=car_item}
        ['{$car_item['longitude']}', '{$car_item['latitude']}']]{if !$car_item@last},{/if}
    {/foreach}
    ];
    </script>
    
    {foreach from=$car_owner item=car_item}
        <tr>
            <td>
                <a href="#">{$car_item['carName']}</a>
            </td>
        </tr>
    {/foreach}