print array in the amount of values of another array

Asked

Viewed 40 times

1

I’m new to php and have the following problem, I wanted to print an array with string values in the amount of values of another array with integer values.

That must be it.

$string = array('a','b','c'); // This is an array with string.
$num = array(3,2,1); // This is an array with the amount of impressions.

The result has to be an array like this.
['a','a','a'], ['a','a'], ['a'], ['b','b','b'], ['b','b'], ['b'], ['c','c','c'], ['c','c'], ['c']

I tried with for, array_slice and array_splice but could not. Can someone give me a direction of how to do this ?

I thank everyone who can help.

  • This looks like a course exercise. Have you tried using a for, foreach? It’s a solution. Try one of these forms that I quoted and put (edit the post) here that I try to direct you. "From PHP 5.4 you can also use the contracted array syntax, which you exchange array() for [] " See https://www.php.net/manual/en/language.types.array.php

  • Complementing, take a look at the array_fill as well

  • Thank you fellow for the direction. Ah! and also it is not course exercise no, it is a script that I am trying to make.

  • By solving put here in case you do any different than the way Euclid did for you. If you have put a solution also to enrich the content of the post

1 answer

0


There is a Function in PHP that can help. Reference array_fill

array_fill ( int $start_index , int $num , mixed $value ). 

And you can do a simple foreach with the two array. So the value to be replicated will be the $string array, and the number of times $num. So, as you yourself defined.

$string = ['a','b','c'];
$num = [3,2,1];

$newArray = [];

foreach($string as $s){
   foreach($num as $n){
      $newArray[] = array_fill(0,$n,$s);   
   }
}

To visualize, you can use var_dump(). Or to get more visual, do two more foreach to view the multidimensional array that was created.

Thus,

foreach($newArray as $n){
   foreach($n as $value){
     echo $value;
  }
  echo "<br/>";
}
  • 1

    Thank you very much mate, I’ll look at this indicated php function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.