【问题标题】:PHP Fatal error: Cannot use string offset as an arrayPHP 致命错误:不能将字符串偏移量用作数组
【发布时间】:2014-12-04 04:10:04
【问题描述】:

面对数组的奇怪情况.. 我正在使用 LinkedIn API 来获取以两种格式返回数据的个人资料信息..

如果用户只有一项教育项目

educations=>education=>school-name
educations=>education=>date
...

如果有多个教育项目

educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...

现在我正在尝试使其保持一致并进行转换

educations=>education=>school-name

educations=>education=>0=>school-name

但是在我认为应该可以工作的代码中出现错误

if(empty($educations['education'][0]['school-name']))
{
    $temp = array();
    $temp['education'][0]=$educations['education'];
    $educations = $temp;
}

“只有一个教育项目”失败,在第一行为 (isset,is_array 和 empty) 生成错误

PHP Fatal error:  Cannot use string offset as an array in ...

print_r 返回

[educations] => Array
    (
        [education] => Array
            (
                     [id] => 109142639
                     [school-name] => St. Fidelis College
                     [end-date] => Array
                         (
                             [year] => 2009
                         )

            )

    )

【问题讨论】:

  • 你能var_dump$educations的内容吗?

标签: php arrays


【解决方案1】:

通常你会这样写作业:

$temp = array(
    "education" => array($educations['education'])
);

为了避免任何索引问题。这也可能解决您的问题。

如果您不确定$educations['education'][0]['school-name'] 的内容,您可以简单地检查每个部分:

if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))

这是因为isset 表现得像一个正常的功能。它以惰性方式接受多个参数。

【讨论】:

    【解决方案2】:

    你想要:

    if(array_key_exists('school-name',$educations['education']))
    {
        $educations['education'] = array($educations['education']);
    }
    

    【讨论】:

      【解决方案3】:

      今天我在我的应用程序中遇到了同样的问题。致命错误:在第 2447 行的 /home/servers/bf4c/bf4c.php 中无法使用字符串偏移作为数组

      第 2447 行

      if (!isset($time_played[$player]["started"])) {
                          $time_played[$player]["started"] = $time;
                      }
      

      $time_played 在别处被覆盖并定义为字符串。因此,请确保您确实使用了唯一的变量名。

      【讨论】:

        【解决方案4】:

        如果您正在运行一个循环并且它会中断,这里有一个提示:

        if( $myArray != "" ){
          // Do your code here 
        
          echo $myArray['some_id'];
        }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多