douhao7677 2018-04-02 22:03
浏览 69
已采纳

从php中的数组中获取对称整数的总数?

ok so i have array for example $arr= "/43sdsd555ksldk66sd"544fdfd";

I take numbers using preg_match_all '/\d+/', and array_map('intval', $zni[0]);

Now the problem is i need to reverse those whole int to see if they are symmetric,like 555 and 66 , and if they are GET A TOTAL OF THEM.(total of only symmetric numbers)

i tried to use function " strrev "and got symmetric numbers, but i don't know how to put them in a one place IF THEY ARE symmetric and calculate them.

<?php
$numbers = "";

if (isset($_GET['submit']))
{
    $numbers = ($_GET['niz']);
    preg_match_all('/\d+/', $numbers, $zni);
    $numtwo= array_map('intval', $zni[0]);
}

foreach ($numtwo as $num)
{
    $reverse = strrev($num);
    var_dump($reverse);

    if ($num == $reverse)
    {
        $reverse = "true";
    } else {
        $reverse = "false";
    }
    var_dump($reverse);
}
  • 写回答

1条回答 默认 最新

  • douling8087 2018-04-02 22:44
    关注

    Since you already got most of the way there and all you were missing basically was to use + or +=, here is an easy example on how to do it:

    $input = "/43sdsd555ksldk66sd544fdfd";
    $total = 0;
    
    preg_match_all('/\d+/', $input, $m);
    foreach ($m[0] as $d)
        if ($d == strrev($d))
            $total += $d;
    
    var_dump($total); // => int(621)
    

    Using intval() is not necessary as PHP will implicitly cast between types as needed.

    Alternatively you can replace the loop with PHP's array_* functions:

    $input = "/43sdsd555ksldk66sd544fdfd";
    
    preg_match_all('/\d+/', $input, $m);
    $total = array_sum(array_filter($m[0], function ($v) { return $v == strrev($v); }));
    
    var_dump($total); // => int(621)
    

    Here we use an anonymous function with array_filter() to generate a new array that only contains palindrome numbers from the original matches which is then given to array_sum().

    So all that's needed to transform your original code into a working example, is introducing a variable and summing up:

    <?php
    $numbers = "";
    
    if (isset($_GET['submit']))
    {
        $numbers = ($_GET['niz']);
        preg_match_all('/\d+/', $numbers, $zni);
        $numtwo= array_map('intval', $zni[0]);
    }
    
    $total = 0; // new variable
    foreach ($numtwo as $num)
    {
        $reverse = strrev($num);
        var_dump($reverse);
    
        if ($num == $reverse)
        {
            $reverse = "true";
            $total += $num; // sum up
        } else {
            $reverse = "false";
        }
        var_dump($reverse);
    }
    
    var_dump($total); // => int(621)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?