数组未显示正确的值

时间:2014-01-29 15:06:08

标签: php

$data['results'] = $this->lawmodel->getuser($lastName);
$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);
foreach ($data['results'] as $row) {
   $my_xp = $row->points;   // the value is 300
}
for ($i = 0; $i < count($xp); $i++) {
   if ($my_xp >= $xp[$i]) {
      $data['level'] = $i+1;
      break;
   }
   else {
      if (isset($xp[$i+1])) {
         if ($my_xp > $xp[$i] && $my_xp <= $xp[$i + 1]) {
            $data['next'] =  $xp[$i+1],;
            break;
         }
         else {
            $data['next'] =  $xp[$i],
            break;
         }
      }
   }
}

我遇到一个问题,$data['level'] = $i+1的输出始终为1.我希望它输出值等于或大于$my_xp的数组的键。

流量: 如果用户的积分是300,那么它应该是lvl2。

Plss..i需要帮助..我在php中的新... :(

1 个答案:

答案 0 :(得分:1)

你的数组

$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);

没有整数键

试试这段代码:

$data['results'] = $this->lawmodel->getuser($lastName);
$xp = array("lvl1" => 0, "lvl2" => 256, "lvl3" => 567);
$key_prefix = 'lvl';
foreach ($data['results'] as $row) {
   $my_xp = $row->points;   // the value is 300
}
$previous_xp = 0;
foreach ($xp as $lvl => $xp_value) {
if ($my_xp >= $xp_value) {
    $data['level'] = $lvl;
} else {
    if ($my_xp > $previous_xp && $my_xp <= $xp_value) {
        $data['next'] =  $xp_value;
    } else {
        $data['next'] =  $previous_xp;
    }
}
$previous_xp = $xp_value;
}