0

Sorry, but I'm not JS master and tbh I'm completly clueless on this one. How can i generate multidmensionall array using smarty in javascript output.

var kreator_elements = new Array();

{foreach $kreator_elements as $element}

if(!kreator_elements[{$element->id_atrib}] instanceof Array)
    var kreator_elements[{$element->id_atrib}] = new Array();

kreator_elements[{$element->id_atrib}][{$element->id}] = new Array();
kreator_elements[{$element->id_atrib}][{$element->id}]['u_img'] = '{$element->getImageLink()}';
kreator_elements[{$element->id_atrib}][{$element->id}]['u_ico'] = '{$element->getIconLink()}';

{/foreach}

tried few approaches, with [] etc. None of them work for me for now. Always get some kind of error in console.

2
  • 2
    Don't mix the two languages like this, it's completely incomprehensible. Try to build a PHP associative object with PHP, and then transmogrify that into a JS object literal with json_encode Commented Feb 27, 2013 at 12:42
  • Oh... thank you. Now only need to figure out how to get element by id_atrib and id reference. Commented Feb 27, 2013 at 13:40

1 Answer 1

1

Try building the associative array in pure PHP, not using Smarty:

$tmp = array();
foreach ($kreator_elements as $element) {
    $tmp[$element->id_atrib][$element->id] = array(
        'u_img' => $element->getImageLink(),
        'u_ico' => $element->getIconLink()
    );
}
$kreator_elements_json = json_encode($tmp);

Make suere that all strings are UTF-8 encoded, or the json_encode will fail. If not, run iconv() on each non unicode string.

The result can be echoed as it is correct javascript object and no smarty is needed.

Always try to use as little languages as possible when building one language in another one. If you really have to, then remember to escape each string, as just one ' sign or a newline could cause syntax error in the generated code.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Indeed that was the right approach. Many thanks to you and Bergi for help! I suggested myself with such appearch since Prestashop developers did it earlier in code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.