1

I get translations from database and want to get generate it in Javascript object, like:

var Lang = {
  eng: {
    txtUserName: 'Username',
    txtLogout: 'Logout'
  },
  dnk: {
    txtUserName: 'Brugernavn',
    txtLogout: 'Afslut'
  }
}

I got stuck in loops, the result I get is not what I need. This is my PHP:

var Lang = {
    <?php
      $allLangs = $this->params->getLanguages;
      foreach ($allLangs as $allLang) :
        echo $allLang->lang_code . ': ';
        echo '{';
        foreach ( $translationsall as $translation ) :
            if ( $translation['it_text'] == 'txtUserName' ) :
              for ( $i = 1; $i <= 1; $i++ ){
                    var_dump($translationsall[$i]);
              }
            endif;
        endforeach;
        echo '},';
        echo "\r\n";
        endforeach;
    ?>
}

And this is what I get:

var Lang = {
  dnk: {array(2) {
    ["it_text"]=>
    string(8) "appTitle"
    ["it_name"]=>
    string(3) "VMS"
  }
  array(2) {
    ["it_text"]=>
    string(8) "appTitle"
    ["it_name"]=>
    string(3) "VMS"
  }
},
eng: {array(2) {
  ["it_text"]=>
  string(8) "appTitle"
  ["it_name"]=>
  string(3) "VMS"
}
array(2) {
  ["it_text"]=>
  string(8) "appTitle"
  ["it_name"]=>
  string(3) "VMS"
}
}

How can I edit my loops to get result I need?

Maybe there is a smarter way to generate Lang object?

And, forgot to mention that I need only few translations, that's why I have this in PHP if:

if ( $translation['it_text'] == 'txtUserName' ) :
  //stuff
endif;

Any ideas are welcome :)

And this what I get from var_dump($translationsall):

array(2748) {
 [0]=>
 array(2) {
   ["it_text"]=>
   string(8) "appTitle"
   ["it_name"]=>
   string(3) "CMS"
 }
 [1]=>
 array(2) {
   ["it_text"]=>
   string(8) "appTitle"
   ["it_name"]=>
   string(3) "CMS"
 }
 [2]=>
  array(2) {
    ["it_text"]=>
    string(9) "txtLogout"
    ["it_name"]=>
    string(6) "Afslut"
  }
  [3]=>
  array(2) {
    ["it_text"]=>
    string(9) "txtLogout"
    ["it_name"]=>
    string(6) "Logout"
  }
  [4]=>
  array(2) {
    ["it_text"]=>
    string(10) "btnRefresh"
    ["it_name"]=>
    string(9) "Hent Igen"
  }
  [5]=>
  array(2) {
    ["it_text"]=>
    string(10) "btnRefresh"
    ["it_name"]=>
    string(7) "Refresh"
  }
 }
3
  • 3
    Would using json_encode() be a better method to build the output data structure? Commented Jun 28, 2018 at 11:26
  • One thing I don't understand is that you loop through the languages and the loop over all of the values in $translationsall. There seems to be no link between the two - especially as your dump of $translationsall has no language indicator. Commented Jun 28, 2018 at 11:41
  • I changed query, so translation results have a lang_code, therefore I created new question. You can find it here: stackoverflow.com/questions/51096078/… Commented Jun 29, 2018 at 7:07

6 Answers 6

1

Please, don't do this. - Make an API call to a PHP backend producing the data you need. - Using either out of the box functions such as $.ajax from jQuery or other prebuilt frameworks will help you achieve this.

If you still want to go down the line of dynamically doing this (your question) - remove var_dump - which is ultimately dumping the type and other details (as it should) and use foreach (key, value) which will help you generate what you need. - But rather going down this dodgy route I'd recommend you take a look at how to serve an API using Laravel or other frameworks.

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

Comments

1

You could pass data from PHP to JS with JSON.
From PHP, you can use json_encode():

echo json_encode($translation);

And in your JS use JSON.parse():

var obj = JSON.parse('{"key":value}');

You can then do:

<?php
$allLangs = $this->params->getLanguages;
$json = json_encode($allLangs);
?>
<script>
    var Lang = JSON.parse('<?php echo $json; ?>');
</script>

Comments

0

As others here have already mentioned; it is a bad idea to dynamically create your javascript like this - I would instead use JSON to serialize and deserialize the data. Anyway, if you insist on dynamic creation; it'll probably be something along the lines of;

var Lang = {
<?php
  $allLangs = $this->params->getLanguages;
  foreach ($allLangs as $allLang) {
    echo $allLang->lang_code . ': {';
        foreach ( $translationsall as $translation ) {
            $total_words_to_translate = count($translation);
            for($i = 0; i <= $total_words_to_translate; $i++){
                if ( $translation['it_text'] == 'txtUserName' ){
                    print("txtUserName: ".$translationsall[$i]);
                }
                if ( $translation['it_text'] == 'txtLogout' ){
                    print("txtLogout: ".$translationsall[$i]);
                }
            }
        }
     echo '},';
     echo "\r\n";
    }
?> }

Its somewhat hard to determine the exact code when we don't know the structure / naming conventions of your database / variables.

Comments

0

Use json_encode:

var Lang = <?php
  $all_langs = $this->params->getLanguages();
  echo json_encode($all_langs);
?>;

1 Comment

var_dump($allLangs) returns this array(2) { [0]=> object(stdClass)#4188 (4) { ["lang_code"]=> string(3) "dnk" ["lang_text"]=> string(5) "Dansk" ["lang_invalid"]=> NULL ["lang_locale"]=> string(2) "da" } [1]=> object(stdClass)#4189 (4) { ["lang_code"]=> string(3) "eng" ["lang_text"]=> string(7) "English" ["lang_invalid"]=> NULL ["lang_locale"]=> string(2) "en" }
0

Not sure how close I am with the data definitions, but I've included them so you can see what I'm assuming and hopefully be able to adjust it to your needs.

The way it works is that it starts at the beginning of $translationsall array and assumes that the $allLangs array is in the same order as the entries ( so in this case the dnk and then the eng values). These it then populates into the output under the language key, with it_text as the key and it_name as the translation.

$translationsall = [["it_text" => "txtLogout", "it_name"=>"Afslut"],
    ["it_text"=> "txtLogout", "it_name"=> "Logout"],
    ["it_text" => "txtLogout2", "it_name"=>"Afslut2"],
    ["it_text"=> "txtLogout2", "it_name"=> "Logout2"]
];

$allLangs = [ (object)["lang_code"=> "dnk"], (object)["lang_code"=> "eng"] ];
$countTrans = count($translationsall);
$out = [];
$i = 0;
while( $i < $countTrans )    {
    foreach ( $allLangs as $language )  {
        $out[$language->lang_code][$translationsall[$i]["it_text"]] = $translationsall[$i]["it_name"];
        $i++;
    }
}

echo json_encode($out, JSON_PRETTY_PRINT);

This prints out

{
    "dnk": {
        "txtLogout": "Afslut",
        "txtLogout2": "Afslut2"
    },
    "eng": {
        "txtLogout": "Logout",
        "txtLogout2": "Logout2"
    }
}

Comments

0

You can try with echo see bellow code :

var Lang = {
<?php
  $allLangs = $this->params->getLanguages;
  foreach ($allLangs as $allLang) :
    echo $allLang->lang_code . ': ';
    echo '{';
    foreach ( $translationsall as $translation ) :
        if ( $translation['it_text'] == 'txtUserName' and $translation['itl_lang_code '] == $allLang->lang_code) :
    echo "txtUserName:'".$translation['it_text']."',txtLogout:'".$translation['it_name']."' ";
          endif;
    endforeach;
       echo '}';
    echo '},';
    echo "\r\n";
    endforeach;
?>
          }

7 Comments

I tried your way, but it's same- I get var Langasd = { dnk: {txtUserName':'Brugernavn' txtUserName':'Username' }}, eng: {txtUserName':'Brugernavn' txtUserName':'Username' }}, };
Only danish text should in dnk:{} and only english in eng:{}
can you edit with out put of $translationsall cuz you need to use a key like this $translationsall[$allLang->lang_code] if $allLang->lang_code exist in $translationsall
var_dump($translationsall) returns all translations from database, like mentionded before: array{[8]=> array(2) { ["it_text"]=> string(9) "txtLogout" ["it_name"]=> string(6) "Afslut" } [9]=> array(2) { ["it_text"]=> string(9) "txtLogout" ["it_name"]=> string(6) "Logout" }}
but how you separate $allLang on $translationsall cuz i dont see a key for lang
|

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.