How to create an array with strings in the amount of values contained in another array

Asked

Viewed 38 times

1


I’m trying to create a new array with the string being displayed in the same amount of values contained in another array. This should be easy, but I’m not getting the logic to create a new array and display these strings according to the amount of values of another array.

Sort of like this.
$A = array('A','B','C','D');<br>
$B = array(4, 2, 1, 1);<br><br>

The result I’m looking for should be like this.

['A','B','C','D']
['A','B']
['A']
['A']

That is, the first letter should appear in the number of times of the first value of $B, the second letter according to the second value of the $B and so on. I have tried to use array_splice within a foreach and it didn’t work.
Can someone give me a hand?

From now on I thank you all.

  • Ask the question how was your attempt to solve the problem.

1 answer

0

I do not know if it is exactly what you asked, because I did not understand what I wanted, but in this case the result on the screen is this

['A','B','C','D']['A','B']['A']['A']

<?php

$A = array('A','B','C','D');
$B = array(4, 2, 1, 1);

$arr = array(1, 2, 3, 4);
foreach ($B as &$value) {
    echo '[';
    for( $i =0; $i < $value; $i++) {
       if( $i+1 < $value)
        echo "'$A[$i]'," ;
       else
        echo "'$A[$i]'" ;
    }
    echo ']';
}
  • 1

    Thanks fellow, but still not what I need. But with this example has helped me a lot to seek a direction.

Browser other questions tagged

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