【问题标题】:Convert to Integer and back to String after calculations计算后转换为整数并返回字符串
【发布时间】:2013-03-24 04:37:33
【问题描述】:

我有一个如下的数组,我把它放入了一个名为 $testcoords 的数组中

array (
  0 => '\'263',
  1 => '252',)

我想提取数值并对其进行操作,然后将它们放回字符串中。我正在尝试使用以下代码:

$tc2 = explode(":",$testcoords);
$tcx = (int)(trim($tc2[0],"'\'");
$tcy = (int)(trim($tc2[1],"'");
$tcx2 = (($tcx)*(600/386));
$tcy2 = (($tcy)*(600/386));
$xtrans = (string)$tcx2;
$ytrans = (string)$tcy2;

到目前为止,我知道修剪功能有效 - 只是 (trim($tc2[0],"'\'") 或 (trim($tc2[1],"'") 返回我的数值两个字符串。

现在我想做的是将这些数值转换为我尝试与修剪函数结合的整数。一旦它们是整数,我想转回字符串并发布结果。

当我尝试这样做时,我没有得到任何结果。直到修剪数据的步骤很好。

例如,如果我只是这样做

$tcx = (trim($tc2[0],"'\'");
$tcy = (trim($tc2[1],"'");

对于上面列出的数组,并将结果回显,我在响应中得到 263 和 252。

感谢有关如何完成其​​余部分的任何指示。

【问题讨论】:

    标签: php arrays string integer


    【解决方案1】:

    这是一个语法错误。您没有认识到这一点,因为您禁用了错误报告。您可以使用 php.ini 设置 display_errors=1log_errors=1 以及 error_reporting=E_ALL 之类的设置来完成。您也可以通过发出以下命令在脚本中执行此操作:

    ini_set('display_errors', 1); // for development 
    ini_set('display_errors', 0); // for production (display_errors would be a security risk)
    ini_set('log_errors', 1); // for both development and production
    ini_set('error_reporting', E_ALL);
    

    错误:转换为 int 时缺少右括号。 )

    使用这个:

    $tcx = (int)(trim($tc2[0],"'\'")); // <-- note the second closing ')'
    $tcy = (int)(trim($tc2[1],"'"));
    

    进一步注意,这可以简化为

    $tcx = (int)(trim($tc2[0],"'\'"); // <-- note the second closing ')'
    $tcy = (int)(trim($tc2[1],"'");
    

    【讨论】:

    • 谢谢。我正在使用 Bluefish 编写代码,一个怪癖是它不会突出显示不匹配,出于某种原因。
    • 阅读我的更新。您应该启用display_errorslog_errors,而不是依赖代码编辑器的语法高亮。 ;)
    【解决方案2】:

    trim 之前的这些行中有一个不必要且未闭合的括号

    $tcx = (int)(trim($tc2[0],"'\'");
    $tcy = (int)(trim($tc2[1],"'");
    

    将这些更改为:

    $tcx = (int)trim($tc2[0],"'\'");
    $tcy = (int)trim($tc2[1],"'");
    

    另外,在开发的时候开启error_reporting,这样的错误你会清楚的看到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 1970-01-01
      • 2011-11-15
      • 2015-10-05
      • 2019-10-16
      相关资源
      最近更新 更多