dsrbb20862 2017-11-01 16:00
浏览 53
已采纳

PHP从相应的计数数组创建多维数组

Using PHP (7.1) with the following data and nested loops, I'm trying to get each host to match the corresponding number in the COUNTS array.

HOSTS:
Array ( 
  0 => 'example/search?results1'
  1 => 'thisone/search?results2'
  2 => 'thesetoo/search?results3'
)

COUNTS:
Array (
  0 => '3'
  1 => '5'
  2 => '7'
)

foreach ( $counts as $count ) {
  foreach ( $hosts as $host ) {
  $t = $count;
    for ($n=0; $n<$t; $n++) {
      $results[] = ++$host;
    }
  continue 2;
  }
}

echo 'THESE ARE ALL THE RESULTS:',PHP_EOL,PHP_EOL,var_dump($results);

RESULTS I'M LOOKING FOR: MULTIDIMENSIONAL ARRAY

Array (
0 => Array (
    0 => 'example/search?results1'
    1 => 'example/search?results1'
    2 => 'example/search?results1'
    )
1 => Array (
    0 => 'thisone/search?results2'
    1 => 'thisone/search?results2'
    2 => 'thisone/search?results2'
    3 => 'thisone/search?results2'
    4 => 'thisone/search?results2'
    )
2 => Array (
    0 => 'thesetoo/search?results3'
    1 => 'thesetoo/search?results3'
    2 => 'thesetoo/search?results3'
    3 => 'thesetoo/search?results3'
    4 => 'thesetoo/search?results3'
    5 => 'thesetoo/search?results3'
    6 => 'thesetoo/search?results3'
    )
)

Notice the number of results per HOSTS corresponds to the COUNTS array.

In the nested for loops above, I'm either getting just one host for all counts or every count for all hosts in a single dimension array. What I need is a multi-dimensional array, but the nested for loop logic is escaping me. I've tried both continue and break in the loops, but no luck. If the loop gets another count, then it skips the host. If it gets another host, then it skips the count.

There is no pattern to either the hosts or the counts array. These will always correspond to each other but they will be random strings/numbers. Thank you for your help.

  • 写回答

4条回答 默认 最新

  • douyu7618 2017-11-01 16:09
    关注

    if count of $hosts and $counts equals:

    $result = [];
    foreach ($hosts as $i => $host) {
        $result[] = array_fill(0, $counts[$i], $host);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥66 换电脑后应用程序报错
  • ¥50 array数据同步问题
  • ¥15 pic16F877a单片机的外部触发中断程序仿真失效
  • ¥15 Matlab插值拟合差分微分规划图论
  • ¥15 keil5 target not created
  • ¥15 C/C++数据与算法请教
  • ¥15 怎么找志同道合的伙伴
  • ¥20 如何让程序ab.eXe自已删除干净硬盘里的本文件自己的ab.eXe文件
  • ¥50 爬虫预算充足,跪巨佬
  • ¥15 滑块验证码拖动问题悬赏