dongpao5658 2015-04-13 08:31
浏览 22
已采纳

如何在PHP中的foreach循环中键入转换变量?

I'm looping through an array using a foreach loop:

$attributes = array( 'drink', 'price', 'amount' );

foreach ( $attributes as $key ) {
    $info[$key] = $key;
}

How can I type cast my $key variable differently each time the loop runs? For example, I need drink to be type string, price to be float and amount to be int.

Please note, this is a simplified example of my code. Type casting the keys before the loop is run isn't suitable in my case.

I tried the following but it didn't seem to work:

$attributes = array( 'drink' => 'string', 'price' => 'float', 'amount' => 'int' );

foreach ( $attributes as $key => $value ) {
    $info[$key] = ($value) $key;
}
  • 写回答

4条回答 默认 最新

  • douzi1986 2015-04-13 08:37
    关注

    This should work for you:

    (Here I use the key to then call either strval(), floatval() or intval())

    $attributes = array("str" => 'drink',"float"=> "10.5","int"=> "10" );
    foreach ( $attributes as $k => $key ) {
        $k.="val";
        $info[$key] = $k($key);
    }
    
    var_dump($info);
    

    output:

    array(3) {
      ["drink"]=>
      string(5) "drink"
      ["10.5"]=>
      float(10.5)
      [10]=>
      int(10)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL