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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀