Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
CodeMilitant Avatar asked Jul 14 '26 08:07

CodeMilitant


2 Answers

if count of $hosts and $counts equals:

$result = [];
foreach ($hosts as $i => $host) {
    $result[] = array_fill(0, $counts[$i], $host);
}
like image 186
Artem Ilchenko Avatar answered Jul 21 '26 20:07

Artem Ilchenko


This question is the perfect usage example for array_map() and array_fill().

$hosts = array(
  0 => 'example/search?results1',
  1 => 'thisone/search?results2',
  2 => 'thesetoo/search?results3',
);

$counts = array(
  0 => '3',
  1 => '5',
  2 => '7',
);

$result = array_map(
    function($host, $count) {
        return array_fill(0, $count, $host);
    },
    $hosts,
    $counts
);
like image 41
axiac Avatar answered Jul 21 '26 20:07

axiac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!