【问题标题】:Error_log: PHP Warning: A non-numeric value encounteredError_log:PHP 警告:遇到非数字值
【发布时间】:2020-01-04 02:58:52
【问题描述】:

更新到 PHP 7.3 后出现以下错误

PHP 警告:在第 3702 行的 /functions.php 中遇到非数字值

第 3702 行:

$total += $rating['rating_score'];

功能代码:

function airkit_get_rating( $post_id ) {

if ( is_numeric($post_id) ) {
    $rating_items = get_post_meta($post_id, 'ts_post_rating', TRUE);
    if ( isset($rating_items) && is_array($rating_items) && !empty($rating_items) ) {
        $total = '';
        foreach($rating_items as $rating) {
            $total += $rating['rating_score'];
        }
        if ( $total > 0 ) {
            $round = intval($total) / count($rating_items);
            $result = round($round, 1);

            if ( is_int($round) ) {
                if ( $round == 10 ) return $result;
                else return $result . '.0';
            } else {
                return $result;
            }
        } else {
            return;
        }
    }
} else {
    return;
}}

我没有 PHP 方面的经验。谁能帮我纠正这个错误?

【问题讨论】:

  • 你应该将$total初始化为0,而不是''
  • 您正在尝试添加一个字符串和一个数字。它会自动将字符串转换为数字,但现在它会产生警告。
  • 其实这不是一个新的警告,我在 PHP 5 中重现了它。升级可能改变了你的默认错误报告级别。

标签: php


【解决方案1】:

改变

$total = '';

$total = 0;

您正在尝试将数字添加到字符串中,但字符串看起来不像数字。空字符串被转换为数字0,所以你得到了正确的总数,但它也会产生一个警告。

【讨论】:

  • 这似乎解决了问题。但是我注意到如果$rating['rating_score']也是一个字符串,仍然会触发同样的错误。
  • 没错,但为什么会是一个字符串?
  • 如果您尝试连接字符串,请使用.,而不是+
猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多