首页 > 解决方案 > PHP 7“不能使用字符串偏移作为数组”

问题描述

我们最近升级到 Php 7.4 并遇到以下代码块的潜在致命错误警报:

$total              = 0;
$balance            = 0;
if (is_array($company['history']) && ($histCount = count($company['history']))) {
    for ($i = $histCount - 1; $i >= 0; $i--) {
        $total   += $company['history'][$i]['amt_total'];
        $balance += $company['history'][$i]['due'];
        $company['history'][ $i ]['balance'] = $balance; // EA flags as potential fatal error
        $company['history'][ $i ]['total']   = $total;   // EA flags as potential fatal error
    }
}

中的每个history元素$company都有(除其他外)amt_total、、、和初始化due,最后两个被初始化为。balancetotal0

EA 标记了指示的两行,说“可能引发 PHP 致命错误(不能将字符串偏移量用作数组)。”

感谢任何可以帮助我理解这里出了什么问题的人。

附加信息有人问定义的代码$company来自哪里......

foreach ($this->orderList as $order) {
    if ($order['amt_paid'] !== $order['real_amt_paid'] && !empty($order['real_amt_paid'])) {
        $order['amt_paid'] = $order['real_amt_paid'];
    }
    $row       = [];
    foreach ($this->customerHistoryColumns as $col) {
        $order[$col[0]] = ($order[$col[0]] === null ? "" : str_replace("&", "&", $order[$col[0]]));
        switch ($col[0]) {
            ...
            case "due":
                $row['due'] = $order['amt_total'] - $order['amt_paid'];
                break;
            ...
            default:
                $row[$col[0]] = $order[$col[0]];
                break;
        }
    }
    $row['balance'] = 0;
    $row['total'] = 0;
    $arr['history'][] = $row;
}
return $arr['history'];

公司本身在别处定义;这只是检索history元素。

FWIW,代码多年来一直完美运行;是升级到 PHP7 引起了这个问题。

标签: php

解决方案


推荐阅读