字符串从Array,str_replace转换?

时间:2011-03-22 13:53:51

标签: php arrays translation

String from array,str_replace?

我有一个数组

 $money = array(
    "USD"=>100,
    "BAT"=>1000,
    "RIEL"=>2000
    );

我定义为常量翻译:

define("const_infor","Your __TYPE__ are:  __AMOUNT__  __CURRENCY__ .<br><br>");

糟糕的方式:

  echo "Your balance are :";//more constant here
  foreach ($money as $currency=>$amount){
      echo $money.$currency."; ";
  }

我尝试输出(GOOD WAYS):

  $tmp1 = "";
  $tmp2 = "";
  foreach ($money as $currency=>$amount){
    $tmp1 .= $money;
    $tmp2 .= $currency;
  }
echo str_replace(ARRAY("__TYPE__","__AMOUNT__","__CURRENCY__"),ARRAY("Balance",$tmp1,$tmp2),const_infor); 

但我想要的是输出应该是:

Your Balance are: 100 USD; 1000 BAT; 2000 RIEL

如何通过$currency。到str_replace

任何人都可以帮我这样做。?

3 个答案:

答案 0 :(得分:1)

我不知道你究竟想做什么,但如果它只是输出 尝试

printf("Your Money %f %f %f", $money["USD"], $money["BAT"], $money["RIEL"]);

答案 1 :(得分:1)

嗯,下面只是一种解析器来做你想做的事情。试试看它是否符合你的需求:

function replace($string, $name = '', $value = '')
{
   if ( !empty($name) )
   {
      str_replace('{'.$name.'}', $value, $string);
   }
}


$string = 'Your balance is {bal1} USD, {bal2} BAT';

$string = replace('bal1', $money['USD'], $string);
$string = replace('bal2', $money['BAT'], $string);
$string = replace('bal3', $money['GBP'], $string);

print $string;

答案 2 :(得分:0)

试试:

foreach ($money as $key => $cur)
  echo $cur.' '. $key;