【问题标题】:Error : Trying to access array offset on value of type int错误:尝试访问 int 类型值的数组偏移量
【发布时间】:2023-02-23 05:44:08
【问题描述】:

我对错误消息“尝试访问 int 类型值的数组偏移量”有疑问我使用 PHP 7.4 版,正如我在网上看到的那样:

非数组的数组式访问

bool、int、float 或资源作为数组(例如 $null["key"])现在将生成通知。

代码是:

 <?php
        foreach($gdata_worksheets As $key => $value ){
            //$key="1361298261";
        ?>
            <option value="<?php echo strToHex($key); ?>"<?php echo $key == $gdata->worksheet_id ? ' selected="selected"' : ''?>><?php echo htmlentities($value, ENT_QUOTES, 'UTF-8');?></option>
            



function strToHex($string){

$hex = '';
for ($i=0; $i<strlen($string); $i++){
    $ord = ord($string[$i]);
    $hexCode = dechex($ord);
    $hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);

}

如何解决这个问题,任何想法?

问候

【问题讨论】:

  • 正确显示代码并提供示例字符串

标签: php


【解决方案1】:

$key可能不是字符串,可以用gettype()查一下。

您可以使用 substr() 访问数字:

for ($i=0; $i<strlen($string); $i++){
    $ord = ord(substr($string, $i, 1));

如果您更喜欢使用数组访问,则必须将 $string 转换为 (string)

function strToHex($string){
    $string = (string)$string;

最终提案可能是:

function strToHex($string)
{
    $result = '';
    $n = strlen($string);
    for ($i = 0; $i < $n; $i++) {
        $c = substr($string, $i, 1);
        $c = ord($c);
        $result .= sprintf('%02X', $c);
    }
    return $result;
}

echo strToHex(1234); // 31323334
echo strToHex('Yop!'); // 596F7021

【讨论】:

  • 嗨@JCH77,是的,在代码变量“String”中是整数类型,我尝试了你的解决方案,也是一样。
  • @mirec 我添加了示例,我的最终提案有效
  • 嗨@JCH77,是的,有效!非常非常感谢你! :)
【解决方案2】:

我有同样的错误,解决方案只是使用 strval($value) 将 int 转换为字符串。

我可以用它来做。

【讨论】:

    猜你喜欢
    • 2021-07-23
    • 2020-05-20
    • 1970-01-01
    • 2020-08-26
    • 2020-12-16
    • 2020-12-11
    • 2021-02-02
    • 1970-01-01
    相关资源
    最近更新 更多