我得到了这个数组:
$allImmunities = array(
'poisonPercent' => '/images/gems/earth.gif',
'earthPercent' => '/images/gems/earth.gif',
'paralyzePercent' => '/images/gems/paralyze.gif',
'deathPercent' => '/images/gems/death.gif',
'energyPercent' => '/images/gems/energy.gif',
'icePercent' => '/images/gems/ice.gif',
'firePercent' => '/images/gems/fire.gif',
'physicalPercent' => '/images/gems/physical.gif',
'holyPercent' => '/images/gems/holly.gif',
'invisiblePercent' => '/images/gems/invisible.gif'
);
和$data变量,它们总是返回这样的东西:
$data = 'physicalPercent:10, icePercent:10, holyPercent:-10';
现在我需要爆炸(?)$data与:获得数组键值或有更好的方法?
我不希望它像这样工作:
$v = explode(':', $data);
如果$v[0]
是fe。physicalPercent
,它会选择
/images/gems/physical.gif
同时,我需要操作:后面的数值,所以我需要像这样工作:
if($v[1] > xx and $v[1] < yy)
选择与$v[0]
匹配的数组值。
对不起,我的英语不好,我需要帮助:)。
如下所示:
foreach(explode(', ', $data) as $prop) {
list($propName, $propVal) = explode(':', $prop);
// $propName would be physicalPercent,
// $propVal would be 10 for the first iteration, etc
// now get the image
$img = $allImmunities[$propName];
echo $img . '<br/>';
}
完整代码(包含您的数据):
<?php
$allImmunities = array(
'poisonPercent' => '/images/gems/earth.gif',
'earthPercent' => '/images/gems/earth.gif',
'paralyzePercent' => '/images/gems/paralyze.gif',
'deathPercent' => '/images/gems/death.gif',
'energyPercent' => '/images/gems/energy.gif',
'icePercent' => '/images/gems/ice.gif',
'firePercent' => '/images/gems/fire.gif',
'physicalPercent' => '/images/gems/physical.gif',
'holyPercent' => '/images/gems/holly.gif',
'invisiblePercent' => '/images/gems/invisible.gif'
);
$data = 'physicalPercent:10, icePercent:10, holyPercent:-10';
foreach(explode(', ', $data) as $prop) {
list($propName, $propVal) = explode(':', $prop);
// $propName would be physicalPercent,
// $propVal would be 10 for the first iteration, etc
// now get the image
$img = $allImmunities[$propName];
echo $img ."'n";
}
输出:$ php game.php
/images/gems/physical.gif
/images/gems/ice.gif
/images/gems/holly.gif
您可以首先分解为键/值对,然后根据它们检索值:
$data = 'physicalPercent:10, icePercent:10, holyPercent:-10';
foreach(explode(', ', $data) as $item)
{
list($key, $value) = sscanf($item, '%[a-zA-Z]:%d');
echo $allImmunities[$key], "'n";
}
演示输出():
/images/gems/physical.gif
/images/gems/ice.gif
/images/gems/holly.gif
使用for循环和爆炸数据来获取信息