回显链接中数组的值

时间:2016-06-05 16:00:39

标签: php arrays echo

我有这个数组

[chest] => Array(
     [id] => 125835
     [name] => Warmongering Gladiator's Chain Armor
     [icon] => inv_chest_mail_raidhunter_p_01
     [quality] => 4
     [itemLevel] => 710
     [tooltipParams] => Array(
                           [set] => Array(
                                     [0] => 125835
                                     [1] => 125838
                                     [2] => 126038)

                           [transmogItem] => 71464
                           [timewalkerLevel] => 100
                                )

我回应了[id],[icon],[quality],[set]

$items = $r['result']['items'];
echo 'chest: ID=' . $items['chest']['id'] . ', quality = ' . $items['chest']['quality'] . ', icon = ' . $items['chest']['icon'] . "\n";
foreach($items['legs']['tooltipParams']['set'] as $value){
    echo ''.$value.':';    
}

现在我需要回显一下html链接中的信息。我试过这样的话:

echo "<a href="//www.wowhead.com/item=. $items['chest']['id'] ." class=". $items['chest']['quality'] .pcs=. $value ."><img src="http://www.wow.zamimg.com/images/wow/icons/large/. $items['chest']['icon'] ." alt="some_text"></a>"

1 个答案:

答案 0 :(得分:0)

正如第一条评论指出的那样,您需要转义要以HTML格式呈现的双引号。您还需要在花括号中用双引号字符串分隔数组索引,以便PHP知道$items['chest']['icon']引用特定值,并且不会尝试单独解析$items

echo "<a href=\"//www.wowhead.com/item={$items['chest']['id']}\" class=\"{$items['chest']['quality']}\" pcs=\"$value\"><img src=\"http://www.wow.zamimg.com/images/wow/icons/large/{$items['chest']['icon']}" alt=\"some_text\"></a>";

还有一些需要注意的事项:

  1. 如果$items['chest']内的值是任何类型的用户输入,请小心在渲染之前使用htmlspecialchars()将其转义以防止XSS
  2. 这是sprintf()恕我直言的一个很好的用例,它消除了转义双引号和分隔数组变量的需要。