【问题标题】:Warning: Illegal string offset 'id' [duplicate]警告:非法字符串偏移 'id' [重复]
【发布时间】:2013-11-07 08:35:32
【问题描述】:

我定义了两个变量如下:

$pic = get_tax_meta($books->term_id,'books_field_id', true);
$imageurl = wp_get_attachment_image_src( $pic[id], 'list-thumb' );

print_r($pic) 结果如下:

Array ( [id] => 302 [src] => http://localhost/mysite/wp-content/uploads/2013/10/apic.jpg )

但是,我从 $pic[id] 收到以下警告:

Warning: Illegal string offset 'id'

知道我做错了什么吗?

【问题讨论】:

    标签: php


    【解决方案1】:

    您需要将数组键用引号括起来,如下所示。所以这个

    $pic[id]
    

    必须是

    $pic['id']
    

    或者

    $pic["id"]
    

    【讨论】:

    • 无论有没有引号(单引号或双引号),我仍然收到相同的警告
    • 密钥真的存在吗?
    • 它对某些人有用,对其他人(如果尚未上传图片)它不存在
    【解决方案2】:

    您需要将id 括在单引号或双引号中:

    $pic["id"]
    

    或者:

    $pic['id']
    

    更多详情请参阅Accessing array elements with square bracket syntax

    【讨论】:

    • 无论有没有引号,我仍然收到相同的警告
    【解决方案3】:

    替换

     $imageurl = wp_get_attachment_image_src( $pic[id], 'list-thumb' );
    

     $imageurl = wp_get_attachment_image_src( $pic["id"], 'list-thumb' );
    

    【讨论】:

    • 无论有没有引号,我仍然收到相同的警告
    【解决方案4】:

    这似乎解决了问题:

    $pic = get_tax_meta($books->term_id,'books_field_id', true);
    if (isset($pic['id'])) {
          $picid = $pic['id'];
    };
    $imageurl = wp_get_attachment_image_src( $picid, 'list-thumb' );
    

    【讨论】:

      猜你喜欢
      • 2014-07-23
      • 2017-09-05
      • 2021-09-30
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 2012-04-09
      相关资源
      最近更新 更多