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 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么