Copy values from a PHP array

Asked

Viewed 796 times

0

I have two arrays dynamics in my system:

Array 1:

$nome { [0] => nome1
        [1] => nome2
}

Array 2:

$contagem { [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
}

These two arrays, are dynamic, can have multiple input numbers, the variavel name may have several names, and the count, several values (up to a hundred), but always following this pattern, for reasons of fitting the company’s standards, my doubt is, assuming the variable $name, has 2 values, as I do to duplicate the variable $count, and that in the duplicate variable I can go each name, ex:

Array 1:

$nome { [0] => nome1
        [1] => nome2
}

Array 2:

$contagem { [0] => nome1
            [1] => nome1
            [2] => nome1
            [3] => nome1
            [4] => nome1

            [5] => nome2
            [6] => nome2
            [7] => nome2
            [8] => nome2
            [9] => nome2
}

PS: in the case of doubling the variable $contagem, was only because it had 2 names in the variable $nome, If it were 3 names, it would triple;

  • The count will always be 5 positions for each name?

  • Thanks for replying @Marcelodeandrade, not this array is dynamic, depends on a calculation done on a previous page.

1 answer

0


Use the function array_fill to create a array with predefined size and value. Ex:

<?php

$nomes = ["José", "Maria"];
$contagem = [1,2,3,4,5,6,7,8,9,10];

$a = [];

foreach($nomes as $nome) {
    $arrTemp = array_fill(0, count($contagem), $nome);
    $a = array_merge($a, $arrTemp);
}

var_dump($a);

Demonstration

  • Perfect @Valdeir Psr, worked perfectly, thanks for helping! Cheers

Browser other questions tagged

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