douxitao8170 2016-10-23 08:39
浏览 38
已采纳

PHP键值对,其中键是动态变量,值是数组?

I am trying to create a 2D array where $multiples[$i] = array(multiples of $i), $i = 1,2,3...

function getMultiples($factor, $start = 0, 10)
{
  $multiples = array();

  for($i = $factor + $start; $i < 10; $i+=$factor)
  $multiples[] = $i;

  return $multiples;
}

for($i = 2; $i < 10; $i++)
{
    $start = 0 ;

    $multiples[$i] = getMultiples($i, $start, 10);
}

However, when I var_dump

$multiples[2] = array(0 => 2)
$multiples[3] = array(0 => 3)
$multiples[4] = array(0 => 4)
...

Each element of $values has been intialized with only the first multiple in each array.

I've tested this with non-numerical key values and it works fine. Static key values also work. The dynamic key value $i seems to the problem, what is going on here?

  • 写回答

1条回答 默认 最新

  • duanleiming2014 2016-10-23 09:41
    关注

    If you want to get the multiples of a number, you need to update the getMultiples as following:

    function getMultiples($factor, $start = 0, $max)
    {
      $multiples = array();
    
      for($i = 2; $i < $max; $i++)
      $multiples[] = $i*$factor;
    
      return $multiples;
    }
    

    What we change?

    1. Loop 10 or $max time for($i = $factor + $start; $i < 10; $i+=$factor) to for($i = 2; $i < $max; $i++).
    2. Find multiple $multiples[] = $i; to $multiples[] = $i*$factor;
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)