繁体   English   中英

不能在 php 中使用字符串偏移量作为数组

[英]Cannot use string offset as an array in php

我正在尝试使用示例 php 代码模拟此错误,但没有成功。 任何帮助都会很棒。

“不能使用字符串偏移量作为数组”

对于 PHP4

...这重现了错误:

$foo    = 'bar';
$foo[0] = 'bar';

对于 PHP5

...这重现了错误:

$foo = 'bar';

if (is_array($foo['bar']))
    echo 'bar-array';
if (is_array($foo['bar']['foo']))
    echo 'bar-foo-array';
if (is_array($foo['bar']['foo']['bar']))
    echo 'bar-foo-bar-array';

(实际上来自bugs.php.net

编辑,

那么为什么错误不会出现在第一个 if 条件中,即使它是一个字符串。

因为 PHP 是一种非常宽容的编程语言,我猜。 我将用我认为正在发生的代码来说明:

$foo = 'bar';
// $foo is now equal to "bar"

$foo['bar'] = 'foo';
// $foo['bar'] doesn't exists - use first index instead (0)
// $foo['bar'] is equal to using $foo[0]
// $foo['bar'] points to a character so the string "foo" won't fit
// $foo['bar'] will instead be set to the first index
// of the string/array "foo", i.e 'f'

echo $foo['bar'];
// output will be "f"

echo $foo;
// output will be "far"

echo $foo['bar']['bar'];
// $foo['bar'][0] is equal calling to $foo['bar']['bar']
// $foo['bar'] points to a character
// characters can not be represented as an array,
// so we cannot reach anything at position 0 of a character
// --> fatal error

一旦我升级到 PHP 7,我就能够重现这一点。当您尝试将数组元素强制转换为字符串时,它会中断。

$params = '';
foreach ($foo) {
  $index = 0;
  $params[$index]['keyName'] = $name . '.' . $fileExt;
}

更改后:

$params = '';

到:

$params = array();

我停止收到错误。 我在这个错误报告线程中找到了解决方案。 我希望这有帮助。

我正在解决一个类似的问题,所以在这里记录以防万一。

__get()方法中,我将给定的参数用作属性,如(简化示例)所示:

function __get($prop) {
     return $this->$prop;
}

...即$obj->fred将访问该类的私有/受保护 fred 属性。

我发现当我需要在这个属性中引用一个数组结构时,它生成了不能使用字符串偏移作为数组错误。 这是我做错了什么以及如何纠正它:

function __get($prop) {
     // this is wrong, generates the error
     return $this->$prop['some key'][0];
}

function __get($prop) {
     // this is correct
     $ref = & $this->$prop;
     return $ref['some key'][0];
}

解释:在错误的例子中,php 将['some key']解释为$prop (字符串)的键,而我们需要它来取消引用 $prop 到位。 在 Perl 中,您可以通过指定 {} 来完成此操作,但我认为这在 PHP 中是不可能的。

在尝试调试一些旧的遗留代码时,我第一次遇到这个错误,现在在 PHP 7.30 上运行。 简化后的代码如下所示:

$testOK = true;

if ($testOK) {
    $x['error'][] = 0;
    $x['size'][] = 10;
    $x['type'][] = 'file';
    $x['tmp_name'][] = 'path/to/file/';
}

最简单的解决方法是在之前将 $x 声明为 array():

$x = array();

if ($testOK) {
    // same code
}

我遇到了这个错误并且很疯狂

我的代码是

$aux_users='';

foreach ($usuarios['a'] as $iterador) { 
#code
if ( is_numeric($consultores[0]->ganancia) ) {
    $aux_users[$iterador]['ganancia']=round($consultores[0]->ganancia,2);
  }
}

更改后$aux_users=''; $aux_users=array();

它发生在我的 php 7.2(在生产服务器中!)但正在使用 php 5.6 和 php 7.0.30 所以要注意! 感谢年轻的迈克尔,我希望它也能帮助你!

当你直接打印print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>)); 然后它显示了这个致命错误Cannot use string offset as an object in . 如果你这样打印

$var = $value['#node']-><YOU_OBJECT>; print_r($var);

你不会得到错误!

我只是想解释一下我对同样问题的解决方案。

我之前的代码(给出相同的错误):

$arr2= ""; // this is the problem and solve by replace this $arr2 = array();
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1= ""; // and this is too
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>"; //and it's($arr2[$i][$j]) give an error: Cannot use string offset as an array
    }
    $td .="</tr>";
}

我的代码之后并解决了它:

$arr2= array(); //change this from $arr2="";
for($i=2;$i<count($arrdata);$i++){
    $rowx = explode(" ",$arrdata[$i]);
    $arr1=array(); //and this
    for($x=0;$x<count($rowx);$x++){
        if($rowx[$x]!=""){
            $arr1[] = $rowx[$x];
        }
    }
    $arr2[] = $arr1;
}
for($i=0;$i<count($arr2);$i++){
    $td .="<tr>";
    for($j=0;$j<count($hcol)-1;$j++){
        $td .= "<td style='border-right:0px solid #000'>".$arr2[$i][$j]."</td>";
    }
    $td .="</tr>";
}

谢谢。 希望它有所帮助,如果我的英语像男孩的房间一样混乱,我很抱歉:D

我相信你问的是 PHP 中的变量插值。

让我们做一个简单的夹具:

$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';

现在我们有一个对象,其中:

print_r($obj);

将给出输出:

stdClass Object
    (
        [foo] => Array
            (
                [0] => bar
            )

        [property] => value
    )

我们有包含字符串“foo”的变量$var

如果您尝试使用:

$give_me_foo = $obj->$var[0];

代替:

$give_me_foo = $obj->foo[0];

结果,您会收到“无法使用字符串偏移量作为数组 [...]”错误消息,因为您尝试执行的操作实际上是将消息$var[0]发送到对象$obj 并且 - 正如您从夹具中看到的那样 - 没有定义$var[0]内容。 变量$var是字符串不是数组

在这种情况下你可以做的是使用花括号,这将确保首先被称为$var内容,然后是消息发送的其余部分:

$give_me_foo = $obj->{$var}[0];

结果是"bar" ,正如您所期望的。

从 PHP 7.1+ 版本开始,不再可能为数组赋值,如下所示:

$foo = ""; 
$foo['key'] = $foo2; 

因为从 PHP 7.1.0 开始,对字符串应用空索引运算符会引发致命错误。 以前,字符串被默默地转换为数组。

错误发生在:

$a = array(); 
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';

然后

echo $a['text1']['text2'];     //Error!!

解决方案

$b = $a['text1'];
echo $b['text2'];    // prints: sometext

..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM