Translate array values write to file php - php

I have a google language translate PHP class you can see here
My array file like this:
$lang['FORUM_LOCK'] = 'Lock';
$lang['FORUM_EDIT'] = 'Edit';
$lang['FORUM_POST'] ='Post';
...
I want to loop through and translate all array values and write to file.
I tried all kinds of methods but cant figure it out :(
Im sure someone has done this before?

You may want to use a foreach construct to iterate through all values of $lang.
Something like this :
$lang_fr = array();
foreach($lang as $key => $val) {
$lang_fr = $gt->translate($val , "en", "fr");
}
You can write then it to a PHP file using fwrite() using the same construct :
fwrite($fp, "\$lang_fr['$key'] ='$val';\n");
Be wary of specials characters though. You may want to use addslashes().

Try to extend Google Translate class:
class ExtendedTranslate extends GoogleTranslateWrapper {
public function translateArray($array, $fromLanguage, $toLanguage) {
foreach ($array as &$item) {
$item = $this->translate($item, $fromLanguage, $toLanguage);
}
return array();
}
}

Related

How to manually iterate over array/object without `foreach` and without `for` with PHP

There is this library https://github.com/halaxa/json-machine (PHP) that allows me to read huge JSON files without loading the entire file to memory. It works great and the way I read the JSON is like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
foreach ($temp as $key => $value) {
echo $value;
}
The problem is that I cant use foreach, I need to only read the JSON as I need. For example, I tried the code below everytime I need to retrieve an element from the array:
echo next($temp);
However it returns and empty string. If I use var_dump(current($temp)) it returns this:
object(JsonMachine\StreamBytes)#2 (1) { ["stream":"JsonMachine\StreamBytes":private]=> resource(10) of type (stream) }
Using the foreach loop works perfectly, but I cant use it, I need to retrieve the elements as I need. How can I do that?
This class already provides a generator, you should be able to do something like this:
$temp = \JsonMachine\JsonMachine::fromFile("teste.json");
$iterator = $temp->getIterator();
$firstItem = $iterator->current();
$iterator->next();
$secondItem = $iterator->current();
$iterator->next();
$thirdItem = $iterator->current();
[Edit] Looks like JsonMachine::getIterator() returns a chained generator, so just change that second line to this:
$iterator = $temp->getIterator()->getIterator();

Laravel Framework - How do i search a specific string in a array?

My problem is that I have a huge array. In this array are the Browser, the user used to get on my website, but also bots and spiders.
It looks like this: Mozilla, Mozilla, Mozillabot, Mozilla, Unicornbot and so on.
I need to get every key in my array, that have 'bot' in it like mozillabot, unicornbot.
But I cant find something.
array_search doesn't work, array_keys too.
Does anyone know a solution in Laravel?
You can use the Crawler Detect library which makes it really easy to identify bots/crawlers/spiders. It can be as simple as a couple of lines of code. Below is a snippet taken from the library's documentation:
use Jaybizzle\CrawlerDetect\CrawlerDetect;
$CrawlerDetect = new CrawlerDetect;
// Check the user agent of the current 'visitor'
if($CrawlerDetect->isCrawler()) {
// true if crawler user agent detected
}
// Pass a user agent as a string
if($CrawlerDetect->isCrawler('Mozilla/5.0 (compatible; Sosospider/2.0; +http://help.soso.com/webspider.htm)')) {
// true if crawler user agent detected
}
You could do something like this...
$newArray = [];
foreach ($array as $value) {
if (str_contains($value, ['bot', 'BOT', 'Bot'])) {
$newArray[] = $value;
}
}
This will cycle through the array and use the laravel str_contains function to determine wether or not the array value has the word 'bot' or variants in it and then add it to a new array.
You can use laravel helper functions
$array = ['Mozilla', 'Mozilla', 'Mozillabot', 'Mozilla', 'Unicornbot'];
$array = array_where($array, function($key, $value)
{
return str_contains($value, 'bot');
});
You can use the array_where helper.
Along with the str_contains string helper like so
$array = ["Mozilla", "Mozilla", "Mozillabot", "Mozilla", "Unicornbot"];
$bots = array_where($array, function ($key, $value) {
return str_contains(strtolower($value),array('bot'));
});
Or with the str_is string helper, which uses pattern matching, like this
$bots = array_where($array, function ($key, $value) {
return str_is('*bot*',strtolower($value));
});
The check is done against lowercase strings to avoid variations on "Bot", "BOT" and so on.

AND in a PHP foreach loop?

Is it possible to have an AND in a foreach loop?
For Example,
foreach ($bookmarks_latest as $bookmark AND $tags_latest as $tags)
You can always use a loop counter to access the same index in the second array as you are accessing in the foreach loop (i hope that makes sense).
For example:-
$i = 0;
foreach($bookmarks_latest as $bookmark){
$result['bookmark'] = $bookmark;
$result['tag'] = $tags_latest[$i];
$i++;
}
That should achieve what you are trying to do, otherwise use the approach sugested by dark_charlie.
In PHP 5 >= 5.3 you can use MultipleIterator.
Short answer: no. You can always put the bookmarks and tags into one array and iterate over it.
Or you could also do this:
reset($bookmarks_latest);
reset($tags_latest);
while ((list(, $bookmark) = each($bookmarks_latest)) && (list(,$tag) = each($tags_latest)) {
// Your code here that uses $bookmark and $tag
}
EDIT:
The requested example for the one-array solution:
class BookmarkWithTag {
public var $bookmark;
public var $tag;
}
// Use the class, fill instances to the array $tagsAndBookmarks
foreach ($tagsAndBookmarks as $bookmarkWithTag) {
$tag = $bookmarkWithTag->tag;
$bookmark = $bookmarkWithTag->bookmark;
}
you can't do that.
but you can
<?php
foreach($keyval as $key => $val) {
// something with $key and $val
}
the above example works really well if you have a hash type array but if you have nested values in the array I recommend you:
or option 2
<?php
foreach ($keyval as $kv) {
list($val1, $val2, $valn) = $kv;
}
No, but there are many ways to do this, e.g:
reset($tags_latest);
foreach ($bookmarks_latest as $bookmark){
$tags = current($tags_latest); next($tags_latest);
// here you can use $bookmark and $tags
}
No. No, it is not.
You'll have to manually write out a loop that uses indexes or internal pointers to traverse both arrays at the same time.
Yes, for completeness:
foreach (array_combine($bookmarks_latest, $tags_latest) as $bookm=>$tag)
That would be the native way to get what you want. But it only works if both input arrays have the exact same length, obviously.
(Using a separate iteration key is the more common approach however.)

Native function to get a special array for PHP

Every day , I have this pattern
- an array of objects
- i make a loop to traverse the array
foreach($arr as $obj){
$arrIds[] = $obj->Id;
$arrNames[] = $obj->Name;
}
I could build a function like arrayFromProperties($Array,$ProperyName) but I was wondering if you know a native php function to do this, or something similar, without having to write a new class/function for this.
As far as I know, you'll have to do this by your own.
Have you tried get_object_vars?
There isn't. It's not very hard to write, either. Feel free to reuse or adapt the following to your liking:
function soa_of_aos($aos)
{
$soa = array();
foreach ($aos as $i => $struct)
foreach ($struct as $field => $value)
if (!isset($soa[$field])) $soa[$field] = array($i => $value);
else $soa[$field][$i] = $value;
return $soa;
}

to print values of an array after extracting the array in php

Please help in code that i am unable to print values of associative array after extracting itself
class display{
protected $variables = array();
function set($name,$value) {
$this->variables[$name] = $value;
}
function render(){
extract($this->variables);
// ?? to print values of $variable array
}
foreach($this->variables as $key => $value) {
echo "{$key}: {$value}\n";
}
And how do you try to print the values? The array itself (it's $varables, not $variable, btw) should not be affected.
Update: For what I can tell by your reply to the other answer, you do not really need to extract array. extract jusst puts the variables into local namespace where they will be harder to enumerate. What you need is to use array as is.
foreach($this->variables as $k => $v) echo "$k: $v\n";
or whatever you want to do with them.
if you are using classes, u will need to have something like
var $variables = array(); or
public $variables = array();
and if you are using structured , you will need to do
global $variables;
inside the function .. but as u are using $this-> it indicates ur using a class. You will have to put in some more code in here to make the situation clear.

Categories