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条)

报告相同问题?

悬赏问题

  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?
  • ¥15 Ubuntu20.04.4.LTS系统如何下载安装VirtualBox虚拟机?
  • ¥15 如何用QDomDocument读取内容为空格的xml数据
  • ¥15 请阅读下面代码,帮我修改下代码