首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这个php-iteration可以写得更短/更好吗?

这个php-iteration可以写得更短/更好吗?
EN

Stack Overflow用户
提问于 2012-11-07 22:15:18
回答 2查看 60关注 0票数 1

代码运行完美,但由于我在重复自己(在编程时我喜欢避免),我想知道这是否可以写得更短/更好?

代码语言:javascript
复制
$start = getLocaleDate($item[0]['start_day']);
$start = $start['day_int'] . ' ' . $start['month_string'];
if ($item[0]['start_houre'] !== '00:00:00') {
    $houre = stripLeadingZero(substr($item[0]['start_houre'], 0, 2));
    $minute = substr($item[0]['start_houre'], 3, 2);
    $start .= ' at' . $houre . 'u' . $minute;
}

$end = getLocaleDate($item[0]['end_day']);
$end = $end['day_int'] . ' ' . $end['month_string'];
if ($item[0]['end_houre'] !== '00:00:00') {
    $houre = stripLeadingZero(substr($item[0]['end_houre'], 0, 2));
    $minute = substr($item[0]['end_houre'], 3, 2);
    $end .= ' at' . $houre . 'u' . $minute;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-11-07 22:18:46

在不更改任何功能的情况下,您可以将其转换为函数:

代码语言:javascript
复制
function getTime($item, $which) {
    $time = getLocaleDate($item[0][$which . '_day']);
    $time = $time['day_int'] . ' ' . $time['month_string'];
    if ($item[0][$which . '_houre'] !== '00:00:00') {
        $houre = stripLeadingZero(substr($item[0][$which . '_houre'], 0, 2));
        $minute = substr($item[0][$which . '_houre'], 3, 2);
        $time .= ' at' . $houre . 'u' . $minute;
    }
    return $time;
}

$start = getTime($item, 'start');
$end = getTime($item, 'end');

*应该注意的是,这段代码没有做任何错误检查/预防,所以如果$item中没有索引0,你就会有一个错误( $item[0]['start_day']$item[0]['end_day']等也是如此)。要处理简单的情况,可以将if (!isset($item[0])) return '';添加到函数的开头(如果需要考虑)。

票数 4
EN

Stack Overflow用户

发布于 2012-11-07 22:17:58

当然可以,你可以写一个函数,传入你的项目和要使用的密钥

代码语言:javascript
复制
function your_function($item, $key) {
  $h = $item[$key.'_houre'];
  $time = getLocaleDate($item[$key. '_day']);
  $time = $end['day_int'] . ' ' . $end['month_string'];
  if ($h !== '00:00:00') {
    $houre = stripLeadingZero(substr($h , 0, 2));
    $minute = substr($h , 3, 2);
    $time .= ' at' . $houre . 'u' . $minute;
    return $time;
  }

}

your_function($item[0], 'end');
your_function($item[0], 'start');
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13271532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档