Php - 将字符串中的数字相乘

时间:2016-02-24 16:02:03

标签: php

实施例 有一个变量(123.4234.1.3。) 我需要爆炸这个(。) 并乘以123 4234 1 3

45.6

我怎么能继续

5 个答案:

答案 0 :(得分:3)

一个班轮!

爆炸,删除array_filter的空白项并使用array_product

$product = array_product(array_filter(explode(".", $formatted)));

参考:array_product

如果需要严格过滤,您可以使用严格比较的回调。

$product = array_product(array_filter(explode(".", $formatted), 
    function ($v){ return (int)$v !== 0; }));

这是Demo

答案 1 :(得分:0)

将所有数字相乘:

$total = 1;

foreach($parcalar as $element){
    $total *= $element;
}

答案 2 :(得分:0)

您需要使用字符串的整数值,如下所示:

import os
import RPi.GPIO as gpio
import time
import socket

## set variables for the machine to ping and pin for the LED
hostname = ['kandicraft.finlaydag33k.nl:25565','google.com:80']
led_pin = 37

## prepare
led_status = gpio.LOW
gpio.setmode(gpio.BOARD)
gpio.setup(led_pin, gpio.OUT, gpio.PUD_OFF, led_status)

## PING FUNCTION GALORE!!
def check_ping(host,port):
    captive_dns_addr = ""
    host_addr = ""
    try:
        host_addr = socket.gethostbyname(host)

        if (captive_dns_addr == host_addr):
            return False

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((host,port))
        s.close()
    except:
        return False

    return True



## Run the script itself infinitely
while True:
    host_up = ""
    for host in hostname:
        if ":" in host:
            temphost, tempport = host.split(":")
            pingstatus = check_ping(temphost, tempport)
            if pingstatus == False:
                print('[' + time.strftime("%d-%m-%Y %H:%M:%S") + '] ' + temphost + ' on port ' + tempport + ' seems to be unreachable!')
                host_up = "False"

    if host_up == "False":
        led_status = gpio.HIGH
    else:
        led_status = gpio.LOW
    gpio.output(led_pin,led_status)
    time.sleep(1)

intval Documentation

除了你的字符串($product= 1; foreach($parcalar as $element){ $product = $product * intval($element); } )在末尾包含一个点之外,explode函数还会返回一个数组:

"12.4.1.3."

最后一个值变为0。 因此,请确保字符串不以点(。)结尾,除非这是您想要的。

答案 3 :(得分:0)

$formatted="123.4234.1.3.";
$numbers = explode(".", $formatted);
$mul = array_reduce($numbers, function ($carry, $value) {
    if ($value === "") { // skip empty values
        return $carry;
    }
    return $carry * $value;
}, 1);
var_dump($mul);

输出:

int(1562346)

array_reduce有人吗? :d

答案 4 :(得分:0)

如果有人感兴趣,这是穴居人的解决方案

$var = "123.12.2";
$tempstring = " ";
$count = 0;
$total = 1;
$length = strlen($var);
for($i=0;$i<=$length;$i++)
{
    if($var[$i]!='.' && $i!=$length)
    {
        $tempstring[$count] = $var[$i];
        $count++;
    }
    else//number ended, multiply and reset positions, clear temporary char array
    {
        $total *= intval($tempstring);
        $count=0;
        $tempstring = " ";
    }
}
echo $total;

将输出2952