【问题标题】:PHP: Pass Array to Function with 2 acceptable variable onlyPHP:仅使用 2 个可接受的变量将数组传递给函数
【发布时间】:2014-05-22 11:11:56
【问题描述】:

如何将数组中的值传递给只能接受 2 个变量的函数。

我创建的函数

function sum_the_time($time1,$time2){
    $times = array($time1, $time2);
    $seconds = 0;
    foreach ($times as $time) {
        list($hour,$minute,$second) = explode(':', $time);
        $seconds += $hour*3600;
        $seconds += $minute*60;
        $seconds += $second;
    }

    $hours = floor($seconds/3600);
    $seconds -= $hours*3600;
    $minutes  = floor($seconds/60);
    $seconds -= $minutes*60;
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
}

当我尝试显示时,它给了我总时间: 这里我如何显示结果。

echo sum_the_time('01:45:22', '17:27:03');

我在哪里宣布时间。

我想在我的数组中传递存储的值 这就是我所做的

$stored_time = array();
for($i=0;$i<count($lang_val);$i++){
    $target_time = $project_time;
    $stored_time[] = $target_time;
}

这将为我的数组 [] 添加一个值。 时间是从生成的脚本中获取的。

我只想知道如何传递我的数组的值。到我创建的功能。 有时我的数组中有 3 个值或我的 5 个左右。

【问题讨论】:

  • 函数的参数不能改吗?
  • 我只想将数组值传递给我的函数。例如: $stored_value ['00:15:00','00:15:00','00:15:00'] 或者有时它只能有 2 个值。我怎样才能将它传递给我的功能?
  • 我的意思是你应该改变你的函数签名。与其接受 2 个变量,不如让它接受一个数组作为参数。您是否有任何机会更改功能?
  • 是的,我需要它来工作。无论如何,我怎样才能使该函数接受数组参数?
  • 这正是以下答案的作用。把你的函数改成function sum_the_time($times),去掉第二行->$times = array(...就可以叫sum_the_time($stored_time)了。

标签: php arrays


【解决方案1】:

重写函数并让它接受一个数组。

function sum_the_time($times){
    $seconds = 0;
    foreach ($times as $time) {
    //...

【讨论】:

    【解决方案2】:

    $times 数组直接传递给function sum_the_time() as

    $times = array($time1, $time2);
    function sum_the_time($times)
    {
        if (count($times) > 0)
        {
           // your code
        }
    }
    

    【讨论】:

    • 怎么样?所有的值都在这个数组中 $stored_time;怎么写?
    • 使用 array_push($stored_time,$target_time); 创建 $stored_time在 for 循环中并将其传递给函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2015-12-17
    • 2011-04-01
    相关资源
    最近更新 更多