首页 > 开发 > PHP > 正文

基于php双引号中访问数组元素报错的解决方法

2024-05-04 22:44:01
字体:
来源:转载
供稿:网友

最近在做微信公众号开发,在一个发送图文接口中,需要把数组元素拼接在XML字符串中

foreach ($itemArr as $key => $value){   $items .= "<item>   <Title><![CDATA[$value['title']]]></Title>    <Description><![CDATA[[$value['description']]]></Description>   <PicUrl><![CDATA[$value['picUrl']]]></PicUrl>   <Url><![CDATA[$value['url']]]></Url>   </item>"; } 

结果竟报如下错误信息:

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in D:/hhp/wamp/www/weixin/wx_sample.php on line 146

从错误信息看是单引号的问题,果断去掉之后就没报错了。然而我就纳闷了,引用下标为字符串的数组元素难道不该加引号吗?到php官方手册去查了关于数组的描述,有一段是这样的:

$arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // This will not work, and will result in a parse error, such as: // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // This of course applies to using superglobals in strings as well print "Hello $arr['fruit']"; print "Hello $_GET['foo']"; 

这里给出了两种错误的写法,当一个普通数组变量或超全局数组变量包含在双引号中时,引用索引为字符串的数组元素,索引字符串不应该再添加单引号。那正确的写法是怎样的呢?于是我继续查找官方手册,找到如下说法:

$arr = array('fruit' => 'apple', 'veggie' => 'carrot');// This defines a constant to demonstrate what's going on. The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie');// The following is okay, as it's inside a string. Constants are not looked for// within strings, so no E_NOTICE occurs hereprint "Hello $arr[fruit]";   // Hello apple// With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}";  // Hello carrotprint "Hello {$arr['fruit']}"; // Hello apple$arr = array('fruit' => 'apple', 'veggie' => 'carrot');// This defines a constant to demonstrate what's going on. The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie');// The following is okay, as it's inside a string. Constants are not looked for// within strings, so no E_NOTICE occurs hereprint "Hello $arr[fruit]";   // Hello apple// With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}";  // Hello carrotprint "Hello {$arr['fruit']}"; // Hello apple

这里给出了三种正确的写法:

第一种写法索引字符串不添加任何引号,此时表示获取索引为字符串fruit的数组元素,输出apple。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表