DeepLcom / deepl-php

Official PHP library for the DeepL language translation API.
MIT License
205 stars 21 forks source link

Question about keys in translated arrays #9

Closed diderich closed 2 years ago

diderich commented 2 years ago

Why does the translation function not retain the key, when translating an array of text?

$to_translate = array('a' => 'Text A', 'b' => 'Text B');
$translations = $translator->translateText($to_translate, 'en-US', 'de');

The result is return as an array indexed 0, 1 rather than indexed using 'a', 'b'. Is there a reason for this behavior?

daniel-jones-deepl commented 2 years ago

Hi @diderich, thanks for the question.

This use-case is not supported; the translateText function is intended for arrays without keys. Internally, the array keys are ignored when passed to array_map for encoding. If we were to support this use-case, it wouldn't be clear whether the keys themselves should also be translated.

You could achieve your desired functionality with a wrapper though:

function translateWithKeys(array $keyedTexts, $translator): array
{
    $keys = array_keys($keyedTexts);
    $results = $translator->translateText($keyedTexts, 'en', 'de');
    return array_combine($keys, $results);
}

...

$to_translate = array('a' => 'Text A', 'b' => 'Text B');
$translations = translateWithKeys($to_translate, $translator);
foreach ($translations as $key => $result) {
    echo $key . ": " . $result->text . PHP_EOL;
}

Note: 'en-US' is not a supported source-language, I changed it to 'en' instead.