Creating array from translated datas and merging an array in PHP - php

I'm designing a site with multi-language support. Our main language is Turkish. I do not want while admin is inserting Turkish data, empty other fields in foreign languages. So when the Turkish data insert in ends with "_tr" columns, in the foreign language fields ends with "_en" and "_de", I want to get from Yandex Translator data which is automatically translated.
Here is my table structure:
My data structure like this which will be inserted:
$data = array(... 'parent_id' => 234, 'date' => "2014-08-31 23:07:47", 'status' => 1);
I want to to add in "..." like this:
$translated = array('fruit_tr' => "Elma", 'fruit_en' => "Apple", 'fruit_de' => "Apfel", 'color_tr' => "Kırmızı", 'color_en' => "Red", 'color_de' => "Rot");
I tried this:
$from_turkish = array('fruit' => "Elma", 'color' => "Kırmızı");
public function Translate ($from_turkish) {
$langs = array("tr", "en", "de");
$translated = array();
foreach ($langs as $lang){
foreach ($from_turkish as $field_name => $value) {
$translated[] = array($field_name.'_'.$lang => YandexTrApi($value, 'tr', $lang));
}
}
return $translated;
}
YandexTrApi function returns translated data. Finally, I used array_merge function like this:
$data_array = array_merge($translated, $data);
But it did not take form like this:
$data_array = array('fruit_tr' => "Elma", 'fruit_en' => "Apple", 'fruit_de' => "Apfel", 'color_tr' => "Kırmızı", 'color_en' => "Red", 'color_de' => "Rot", 'parent_id' => 234, 'date' => "2014-08-31 23:07:47", 'status' => 1);

array_merge($translated, $data) is fine and $translated + $data would give the same result in this case, but...
$translated[] = array($field_name.'_'.$lang => YandexTrApi($value, 'tr', $lang));
...this way you'll push new arrays inside $translated array. You need to add new keys only - try this instead:
$translated[$field_name.'_'.$lang] = YandexTrApi($value, 'tr', $lang);
Also the foreach() loops nested like this will give you slightly different order, but I guess you don't need it to match db (as your ... part may be placed before parent_id key).

Related

PHP - foreach loop not return all keys and values [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 4 months ago.
I have an array in my php code
$list = array(
'RETAIL' => 'SUPERMARKET'
'RETAIL' => 'BAR'
'RETAIL' => 'DEP. MARKET'
'BUSINESS' => 'HOTEL'
'BUSINESS' => 'PUB'
'OTHER' => 'GROCERY'
'OTHER' => 'BUTCHERY'
// I have 20+ items
);
foreach( $list as $type => $name ){
var_dump($type,$name);
}
//var_dump() output
// RETAIL SUPERMARKET
// BUSINESS HOTEL
// OTHER BUTCHERY
I'm facing the problem that when I try to loop the array only three values will be returned and the rest are ignored. How I can fix this?
I'm trying to loop the array to save the data into a custom wordpress database. With the same way I've successfully looped another array inserted the keys and values into the db.
I think a better structure for your array would something like this
$list = [
'RETAIL' => [
'BAR',
'RESTAURANT'
]
];
And you could loop over like so
foreach ($list as $businessType => $businesses) {
foreach ($businesses as $business) {
echo "<li>{$business}</li>";
}
}
Just an example
As a general way of handling instances where you have more than one element to each piece of data (even when it's not in a tree structure like this may be), you should structure each item in the list as either an array or object, eg:
$list_of_arrays = [
['RETAIL', 'SUPERMARKET'],
['RETAIL', 'BAR'],
['RETAIL', 'DEP. MARKET'],
];
foreach( $list_of_arrays as $array ){
echo "<li>{$array[0]} {$array[1]}</li>";
}
or
$list_of_objects = [
(object)['type' => 'RETAIL', 'subtype' => 'SUPERMARKET'],
(object)['type' => 'RETAIL', 'subtype' => 'BAR'],
(object)['type' => 'RETAIL', 'subtype' => 'DEP. MARKET'],
];
foreach( $list_of_objects as $object ){
echo "<li>{$object->type} {$object->subtype}</li>";
}
Maybe I show heavily but as you only have two data for each entity, why your table is not built like this at the base...?
$list = array(
'SUPERMARKET'=>'RETAIL',
'BAR'=>'RETAIL',
'DEP. MARKET'=>'RETAIL',
'HOTEL'=>'BUSINESS',
'PUB'=>'BUSINESS',
'GROCERY'=>'OTHER',
'BUTCHERY'=>'OTHER'
// I have 20+ items
);
You do have keys that uniquely identify entities.

PHP - Optional JSON field

I would like to output a JSON string with an optional fields.
Right now I do it as simple as:
echo json_encode(array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
));
Now, say, I would like to include/exclude the 'asd' element based on some logic (using an inline if or some function or something else).
I have no idea how to do it, because, AFAIK, there is no such type in PHP that can force json_encode to skip this field - everything returns null or empty fields but does not skip the field itself.
Any ideas someone?
do you mean something like this:
$arr = array(
array(
'qwe' => 1,
'asd' => 2,
'zxc' => 3
),
array(
'qwe' => 4,
'asd' => '',
'zxc' => 6
)
);
foreach ($arr as $key => $row) {
if ($row['asd'] == '') {
unset($arr[$key]['asd']);
}
}
echo json_encode($arr);

Copying a multidimensional array

I get() an multidimensional array and store it inside the $products variable.
I need to Make a copy of that array to create it into a new Webshop because the export provided by the API does not work so I have created this script to copy the data:
foreach ($products as $id => $product) {
$copy = $products[$id];
$createdProducts = $apiSkylux->products->create(
array(
'id' => $copy['id'],
'createdAt' => $copy['createdAt'],
'updatedAt' => $copy['updatedAt'],
'isVisible' => $copy['isVisible'],
'visibility' => $copy['visibility'],
'data01' => $copy['data01'],
'data02' => $copy['data02'],
'data03' => $copy['data03'],
'url' => $copy['url'],
'title' => $copy['title'],
'fulltitle' => $copy['fulltitle'],
'description' => $copy['description'],
'content' => $copy['content'],
'set' => $copy['set'],
'brand' => $copy['brand'],
'categories' => $copy['categories'],
'deliverydate' => $copy['deliverydate'],
'image' => $copy['image'],
'images' => $copy['images'],
'relations' => $copy['relations'],
'reviews' => $copy['reviews'],
'type' => $copy['type'],
'attributes' => $copy['attributes'],
'supplier' => $copy['supplier'],
'tags' => $copy['tags'],
'variants' => $copy['variants'],
'movements' => $copy['movements'],
)
);
}
The copy is working. But i thought #2016 and all, can't this be achieved with less lines of code?
This is what I receive with var_dump of the first array:
var_dump($products[0]);
exit;
//result
array(28) {
["id"]=>
int(26136946)
//rest of array
So I can see the array has a number (28) , what does this represent?
I've tried several attempts, closest attempt was :
$copy = $products[$id];
$createProducts = $products;
$createdProducts = $apiSkylux->products->create($createProducts);
But then I also got an error : Invalid data input
Can I copy the data from the array easier then the method I am currently using?
array(
'id' => $copy['id'],
...
)
This can be reduced to simply:
$copy
Yes, reassigning every single key into a new array is the same as using the original array in the first place.
foreach($products as $id => $product){
$copy = $products[$id];
This can be reduced to:
foreach ($products as $product){
$copy = $product;
Obviously you could leave out $copy entirely and just use $product.
Bottom line:
foreach ($products as $product) {
$createdProducts = $apiSkylux->products->create($product);
}
What you do with $createdProducts I don't know; you don't seem to be doing anything with it inside the loop, so at best it'll hold the last product after the loop, so is probably superfluous.
Probably you could do:
array_map([$apiSkylux->products, 'create'], $products);
or
$createdProducts = array_map([$apiSkylux->products, 'create'], $products);
depending on whether you need the return values or not.
So I can see the array has a number (28) , what does this represent?
It means it's an array with 28 elements in it.
This doesn't make any sense. Simply use the $product variable within the loop. Done!

Optimization of an algorithm performed on a big array in PHP

I have a query that populates an array from the database. In some cases, this query returns a great amount of data, (let's say for purpose of an example, 100.000 records). Each row of the database has at least 6 or 7 columns.
$results = [
['id' => 1, 'name' => 'name', 'status' => true, 'date' => '10-01-2012'],
['id' => 2, 'name' => 'name 2', 'status' => false 'date' => '10-01-2013'],
...
]
I need to perform a substitution of some of the data inside the $results array, based on another one that give me some information about how i would change the values in the rows.
$model = [
'status' => ['function' => 'formatStatus', params => ['status']],
'date' => ['function' => 'formatDate', params => ['date']]
]
Now that i have all the data and what do i do with it i have the following routine.
foreach ($results as &$itemResult) {
$oldValues = $itemResult;
foreach ($itemResult as $attribute => &$value) {
if (isset($model[$attribute]['function'])) {
$function = $model[$attribute]['function'];
$params = $model[$attribute]['params'];
$paramsSize = count($params);
for ($i = 0; $i < $paramsSize; $i++) {
$newParams[] = $oldValues[$params[$i]];
}
$itemResult[$attribute] = call_user_func_array([$this, $function], $newParams);
$newParams = null;
}
}
}
So, for each attribute for each row of my data array, i run check for the existence of a function and params information. When the attribute in question needs to be replaced, i call the function via call_user_func_array and replace the value with the function return value.
Also notice that i am replacing the current array, not creating another, by passing the reference &$itemResult inside the loop, so in the end, i have the same array from the beginning but with all columns that needed to be replaced with its new values.
The thing is, for little arrays, this method is quite good. But for big ones, it becomes a pain.
Could you guys provide me some alternative to the problem?
Should i use another data structure instead of the PHP array?

Need help about array

What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.

Categories