不能在 php 中使用字符串偏移量作为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1873970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot use string offset as an array in php
提问by rampr
I'm trying to simulate this error with a sample php code but haven't been successful. Any help would be great.
我正在尝试使用示例 php 代码模拟此错误,但没有成功。任何帮助都会很棒。
"Cannot use string offset as an array"
“不能使用字符串偏移量作为数组”
回答by Bj?rn
For PHP4
对于 PHP4
...this reproduced the error:
...这重现了错误:
$foo = 'bar';
$foo[0] = 'bar';
For PHP5
对于 PHP5
...this reproduced the error:
...这重现了错误:
$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';
(From bugs.php.netactually)
(实际上来自bugs.php.net)
Edit,
编辑,
so why doesn't the error appear in the first if condition even though it is a string.
那么为什么错误不会出现在第一个 if 条件中,即使它是一个字符串。
Because PHP is a very forgiving programming language, I'd guess. I'll illustrate with code of what I think is going on:
因为 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
回答by Michael Sayer
I was able to reproduce this once I upgraded to PHP 7. It breaks when you try to force array elements into a string.
一旦我升级到 PHP 7,我就能够重现这一点。当您尝试将数组元素强制转换为字符串时,它会中断。
$params = '';
foreach ($foo) {
$index = 0;
$params[$index]['keyName'] = $name . '.' . $fileExt;
}
After changing:
更改后:
$params = '';
to:
到:
$params = array();
I stopped getting the error. I found the solution in this bug report thread. I hope this helps.
我停止收到错误。我在这个错误报告线程中找到了解决方案。我希望这有帮助。
回答by artfulrobot
I was fighting a similar problem, so documenting here in case useful.
我正在与类似的问题作斗争,所以在这里记录以防万一。
In a __get()method I was using the given argument as a property, as in (simplified example):
在一个__get()方法中,我使用给定的参数作为属性,如(简化示例):
function __get($prop) {
return $this->$prop;
}
...i.e. $obj->fredwould access the private/protected fred property of the class.
...ie$obj->fred将访问该类的私有/受保护 fred 属性。
I found that when I needed to reference an array structure within this property it generated the Cannot use String offset as array error. Here's what I did wrong and how to correct it:
我发现当我需要在这个属性中引用一个数组结构时,它生成了不能使用字符串偏移作为数组错误。这是我做错了什么以及如何纠正它:
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];
}
Explanation: in the wrong example, php is interpreting ['some key']as a key to $prop(a string), whereas we need it to dereference $prop in place. In Perl you could do this by specifying with {} but I don't think this is possible in PHP.
解释:在错误的例子中,php 被解释['some key']为$prop(一个字符串)的一个键,而我们需要它来取消引用 $prop 到位。在 Perl 中,您可以通过指定 {} 来完成此操作,但我认为这在 PHP 中是不可能的。
回答by alexanderesmar
I was having this error and a was nuts
我遇到了这个错误并且很疯狂
my code was
我的代码是
$aux_users='';
foreach ($usuarios['a'] as $iterador) {
#code
if ( is_numeric($consultores[0]->ganancia) ) {
$aux_users[$iterador]['ganancia']=round($consultores[0]->ganancia,2);
}
}
after changing $aux_users='';to $aux_users=array();
更改$aux_users='';为后$aux_users=array();
it happen to my in php 7.2 (in production server!) but was working on php 5.6 and php 7.0.30 so be aware! and thanks to Young Michael, i hope it helps you too!
它发生在我的 php 7.2(在生产服务器中!)但正在使用 php 5.6 和 php 7.0.30 所以要注意!感谢年轻的迈克尔,我希望它也能帮助你!
回答by dev101
I had this error for the first time ever while trying to debug some old legacy code, running now on PHP 7.30. The simplified code looked like this:
在尝试调试一些旧的遗留代码时,我第一次遇到这个错误,现在在 PHP 7.30 上运行。简化后的代码如下所示:
$testOK = true;
if ($testOK) {
$x['error'][] = 0;
$x['size'][] = 10;
$x['type'][] = 'file';
$x['tmp_name'][] = 'path/to/file/';
}
The simplest fix possible was to declare $x as array() before:
最简单的解决方法是在之前将 $x 声明为 array():
$x = array();
if ($testOK) {
// same code
}
回答by Y Rahman
I just want to explain my solving for the same problem.
我只是想解释一下我对同样问题的解决方案。
my code before(given same error):
我之前的代码(给出相同的错误):
$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>";
}
my code after and solved it:
我的代码之后并解决了它:
$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>";
}
Thank's. Hope it's helped, and sorry if my english mess like boy's room :D
谢谢。希望它有所帮助,如果我的英语像男孩的房间一样混乱,我很抱歉:D
回答by Hemangi Gokhale
When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));then it shows this fatal error Cannot use string offset as an object in.
If you print like this
当您直接打印时,print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));它会显示此致命错误Cannot use string offset as an object in。如果你这样打印
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
You won't get the error!!
你不会得到错误!
回答by Michal Gow
I believe what are you asking about is a variable interpolation in PHP.
我相信你问的是 PHP 中的变量插值。
Let's do a simple fixture:
让我们做一个简单的夹具:
$obj = (object) array('foo' => array('bar'), 'property' => 'value');
$var = 'foo';
Now we have an object, where:
现在我们有一个对象,其中:
print_r($obj);
Will give output:
将给出输出:
stdClass Object
(
[foo] => Array
(
[0] => bar
)
[property] => value
)
And we have variable $varcontaining string "foo".
我们有$var包含字符串“foo”的变量。
If you'll try to use:
如果您尝试使用:
$give_me_foo = $obj->$var[0];
Instead of:
代替:
$give_me_foo = $obj->foo[0];
You get "Cannot use string offset as an array [...]" error message as a result, because what you are trying to do, is in fact sending message $var[0]to object $obj. And - as you can see from fixture - there is no content of $var[0]defined. Variable $varis a stringand not an array.
结果,您会收到“无法将字符串偏移用作数组 [...]”错误消息,因为您尝试执行的操作实际上是$var[0]向 object发送消息$obj。并且 - 正如您从夹具中看到的那样 - 没有$var[0]定义的内容。变量$var是字符串而不是数组。
What you can do in this case is to use curly braces, which will assure that at first is called content of $var, and subsequently the rest of message-sent:
在这种情况下你可以做的是使用花括号,这将确保首先被称为内容的$var,然后是消息发送的其余部分:
$give_me_foo = $obj->{$var}[0];
The result is "bar", as you would expect.
结果"bar"如您所料。
回答by Grigoreas P.
The error occurs when:
错误发生在:
$a = array();
$a['text1'] = array();
$a['text1']['text2'] = 'sometext';
Then
然后
echo $a['text1']['text2']; //Error!!
Solution
解决方案
$b = $a['text1'];
echo $b['text2']; // prints: sometext
..
..

