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

报告相同问题?

悬赏问题

  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败