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"
}
}
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.
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>
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.
Use json_encode:
var Lang = <?php
$all_langs = $this->params->getLanguages();
echo json_encode($all_langs);
?>;
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"
}
}
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;
?>
}
Related
Looking to take the data from two API endpoints and merge them into one array using PHP.
While I'm aware of functions like array_merge, not actually looking to append the data, more like map it together at the end. Below is an example of what I'm looking to achieve.;
$api1_endpoint = esc_url_raw( "http://api.com/endpoint" );
$api2_endpoint = esc_url_raw( "http://api.com/endpoint2" );
$api1 = json_decode( $api1_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["productColor"]=> string(3) "red" }
$api2 = json_decode( $api2_endpoint);
// {["sku"]=> string(12) "850661003403" ["productName"]=> string(16) "Product 1" ["quantityAvailable"]=> float(5) }
$combined_apis = // function to combine $api1 and $api2 by ["sku"] or other key
foreach($combined_apis as $combined){
echo $combined->sku;
echo $combined->quantityAvailable;
}
Here is the function for that
public function combine_api_result($api1, $api2) {
$output = $api1;
foreach($api2 as $key => $value) {
if ( ! isset($output[$key])) {
$output[$key] = $value;
}
}
return $output;
}
I am making a code that grab a url part, take values and then set on list.
Problem is on list
if (in_array($term->term_id, $regions)) {
$selected_region = 'selected';
}
else {
$selected_region = 'not';
}
This code does work, always return not.
if ($term->term_id == 2) {
$selected_region = 'varbut?';
}
This work.
$regions is variable and return this:
array(2) { [0]=> string(2) "17" [1]=> string(1) "2" }
Where is the problem to use $term_id?
$term_id with var_dump returns int(17) int(2)
On other pages, single page with only one term is working and code is this:
<?php
$id = get_the_ID();
$postterms = wp_get_post_terms($id, 'destinations'); // get post terms
$parentId = $postterms[0]->term_id; // get parent term ID
?>
<?php if (!in_array($parentId, $regions)): ?>
Why is not working on that selected function? int and string values?
Here is a full term get code:
$custom_terms = get_terms(array($taxonomies), $args);
foreach($custom_terms as $term){
if (in_array($term->term_id, $regions)) {
$selected_region = 'selected';
}
else {
$selected_region = 'not';
}
if ($term->term_id == 2) {
$selected_region = 'varbut?';
}
echo $selected_region;
var_dump($term->term_id);
}
}
It's like you said;
$regions : array(2) { [0]=> string(2) "17" [1]=> string(1) "2" }
$term->term_id : int(2)
How about converting your $regions to ints?
I have the following code:-
if( $featured_query->have_posts() ): $property_increment = 0;
while( $featured_query->have_posts() ) : $featured_query->the_post();
$town = get_field('house_town');
$a = array($town);
$b = array_unique($a);
sort($b);
var_dump($b);
$property_increment++; endwhile; ?>
<?php endif; wp_reset_query();
var_dump(b) shows:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" }
var_dump($town) shows:-
string(10) "Nottingham" string(9) "Leicester" string(9) "Leicester" string(11) "Mountsorrel" string(12) "Loughborough" string(12) "Loughborough"
var_dump($a) shows:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" }
What I want to do is get the unique vales of $town and output them into a select option:-
<select>
<option value="Leicester">Leicester</option>';
<option value="Loughborough">Loughborough</option>';
<option value="Mountsorrel">Mountsorrel</option>';
</select>';
In alpha as above, any help would be much appreciated.
#collect all get_field('house_town') in while
$collect[] = get_field('house_town');
#then do the work
$html = implode('',
array_map(
function($a){
return "<option value='{$a}'>{$a}</option>";
},
array_unique($collect)
)
);
Your array needs to be un-nested with array_column before you sort it and make it unique. So after you initialised $a, continue like this:
$b = array_unique(array_column($a, 0));
sort($b);
and then make the HTML:
$html = "";
foreach($b as $town) {
$html .= "<option value='$town'>$town</option>";
}
echo "<select>$html</select>";
If you don't have array_column, then you can use this replacement:
function array_column($arr, $column) {
$res = array();
foreach ($arr as $el) {
$res[] = $el[$column];
}
return $res;
}
Here's a summary of Chris G's comment and trincot's code snippet for generating the HTML code.
Note: for testing purposes I have created the $town array manually here. Replace it by your statement $town = get_field('house_town');
<?php
$town = array(
"Nottingham",
"Leicester",
"Leicester",
"Mountsorrel",
"Loughborough",
"Loughborough"
);
// $town = get_field('house_town');
$html = "";
$town = array_unique($town);
sort($town);
foreach($town as $xtown) {
$html .= "<option value='$xtown'>$xtown</option>";
}
echo "<select>$html</select>";
?>
Basic/ General unique usage in while/ foreach loop
// refer to
$a = array($town); // $a in while/ foreach loop
if(current($a) != next($a)) {
// do your query here // get required unique here
}
// Note: caring and sharing
array(1) {
["album_name"]=>
string(12) "Cover Photos"
}
array(1) {
["cover"]=>
string(111) "url"
}
array(1) {
["album_name"]=>
string(24) "Fun in Your Name! Photos"
}
array(1) {
["cover"]=>
string(108) "url"
}
This is what it return when I do a var_dumpto my variable, I tried a normal foreach:
<?php
foreach ($fb_albums as $my_albumsdata):
echo $my_albumsdata['cover'];
endforeach;
?>
But doesn't work...
Try this:
for($i=0; $i < count($yourArray); $i += 2) {
$name = $yourArray[$i]["album_name"]
$cover = $yourArray[$i+1]["cover"]
}
But, I think you must change the organisation of the Array.
assuming that you have an array of those four arrays....
the problem would seem to be that not every $my_albumsdata contains a "cover".
if(array_key_exists("cover", $my_albumsdata)) echo $my_albumsdata["cover"];
^should be a quick fix, but lacking context, I'm not sure if this works for you.
I have the following XML array:
["link"]=>
array(2) {
[0]=>
object(SimpleXMLElement)#311 (1) {
["#attributes"]=>
array(3) {
["type"]=>
string(9) "text/html"
["href"]=>
string(48) "http://twitter.com/bob/statuses/1226112723"
["rel"]=>
string(9) "alternate"
}
}
[1]=>
object(SimpleXMLElement)#312 (1) {
["#attributes"]=>
array(3) {
["type"]=>
string(9) "image/png"
["href"]=>
string(59) "http://a3.twimg.com/profile_images/226895523/Dan_normal.png"
["rel"]=>
string(5) "image"
}
}
}
It's inside a bigger array, I need to get the first and second hef attribute seperatly so that I can put one href as a <a> link and another with a <img>.
How can I output each href rather than both together?
Currently trying this:
foreach($entry->link as $link) {
echo $link->attributes()->href;
}
$url = 'http://api.twitter.com/1/favorites/bob.atom';
$feed = simplexml_load_file($url);
$testStop = 0;
foreach($feed->entry as $entry) {
echo 'title: ', $entry->title, "\n";
// store all link/#href in a hashtable
// so you can access them in any order you like
// without resorting to xpath or alike.
$links = array();
foreach($entry->link as $link) {
$links[(string)$link['rel']] = (string)$link['href'];
}
if ( isset($links['image']) ) {
echo '<img src="', $links['image'], '" />', "\n";
}
if ( isset($links['alternate']) ) {
echo '<a href="', $links['alternate'], '" />alternate</a>', "\n";
}
echo "----\n";
if ( 2 < ++$testStop ) die;
}
(currently) prints
title: kolchak: Sometimes I think I need a new butler. But then it's like "Nah, he's still got one thumb. We good."
<img src="http://a1.twimg.com/profile_images/668496250/Picture_14_normal.jpg" />
<a href="http://twitter.com/kolchak/statuses/10648055680" />alternate</a>
----
title: shitmydadsays: "War hero? No. I was a doc in Vietnam. My job was to say "This is what happens when ."
<img src="http://a3.twimg.com/profile_images/362705903/dad_normal.jpg" />
<a href="http://twitter.com/shitmydadsays/statuses/10580558323" />alternate</a>
----
title: shitmydadsays: "I lost 20 pounds...How? I drank bear piss and took up fencing. How the you think, son? I exercised."
<img src="http://a3.twimg.com/profile_images/362705903/dad_normal.jpg" />
<a href="http://twitter.com/shitmydadsays/statuses/10084782056" />alternate</a>
----
But you might also be interested in xsl(t)
You can access the href attributes using normal array/object access. Just store them in an array for later use:
$hrefs = array();
foreach($array['links'] as $links) {
foreach($links->attributes as $key>=$value) {
if('href' == $key) {
$hrefs[] = $value;
}
}
}
// $href[0] = "http://twitter.com/bob/statuses/1226112723"
// $href[1] = "http://a3.twimg.com/profile_images/226895523/Dan_normal.png"
This makes use of SimpleXMLElement's attributes() method.
I don't think that you can access the attributes directly ($elment->#attributes) as this is not a valid syntax.
First href - $xml['link'][0]->attributes()->href
Second href - $xml['link'][1]->attributes()->href