簡體   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