简体   繁体   中英

PHP Function Inside of An Array?

Here is what I have so far:

$arrayPrices = array(
    translate($lang_type, "A/C System Evaluation") => "19.95",
    translate($lang_type, "A/C Evaluation & Recharge") => "99.00"
);

And my translate function is:

function translate($to_lan, $text) {
if($to_lan == "en") {

    return $text;

} else {

    $translate_feed = @file_get_contents('http://api.microsofttranslator.com/v2/Http.svc/Translate?appId=' . BING_APPID . '&text=' . urlencode($text) . '&from=en&to=' . $to_lan . '');
    $translate = simplexml_load_string($translate_feed);

    return ($translate_feed === false) ? $text : $translate[0];
   }
 }

For some reason, I can't display that translate function inside of my PHP Array.

If I type in echo translate($lang_type, "A/C System Evaluation"); it works just fine and translates. But when used in that array it just returns blank.

Does anyone have any idea what I can do?

From the PHP Array docs :

The key can either be an integer or a string. The value can be of any type.

Put your keys in string vars first,like:

$var1 = translate($lang_type, "A/C System Evaluation");
$var2 = translate($lang_type, "A/C Evaluation & Recharge");

$arrayPrices = array(
    "$var1" => 19.95
    "$var2" => 29.95
);

That should work fine.

does this work:

$arrayPrices[translate($lang_type, "A/C System Evaluation")]= "19.95";
$arrayPrices[translate($lang_type, "A/C Evaluation & Recharge")] = "99.00";

I presume you want to be able to add extensively to that product list without having to mess around with temporary variables a great deal. This is one of those situations where I'd do a post-processing run on the array, like so:

$arrayPrices = array(
    "A/C System Evaluation" => "19.95",
    "A/C Evaluation & Recharge" => "99.00",
    // ... etcetera ...
);

$keys = array_keys( $arrayPrices );    
foreach( $keys as $keyText )
{
    $translatedKeyText = translate($lang_type, $keyText);
    if ( $translatedKey != $keyText )
    {
        $arrayPrices[$translatedKeyText] = $arrayPrices[$keyText];
        unset( $arrayPrices[$keyText] );
    }
}

If you use temporary variables, you'll have to add logic for every new entry to your original array. That sounds like a maintenance hassle to me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM