Search code examples
phpmultidimensional-arraycorresponding-records

PHP Create Multidimensional Array from Corresponding Counts Array


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.


Solution

  • if count of $hosts and $counts equals:

    $result = [];
    foreach ($hosts as $i => $host) {
        $result[] = array_fill(0, $counts[$i], $host);
    }