PHP使用数据键获取数组值

时间:2011-07-27 06:13:24

标签: php arrays

我得到了这个数组:

   $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]匹配的数组值。

对不起我的英语,我需要帮助:)。

3 个答案:

答案 0 :(得分:2)

下面的内容,也许是:

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

答案 1 :(得分:0)

使用for循环并展开数据以获取信息。

答案 2 :(得分:0)

您可以先爆炸键/值对,然后根据它们检索值:

$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";
}

输出(Demo):

/images/gems/physical.gif
/images/gems/ice.gif
/images/gems/holly.gif