Numeric sequence loop in PHP

Asked

Viewed 765 times

3

Good morning

I have the result in MYSQL

01
03
04
06
11

I need a solution that fills with 2 zeros where the numerical sequence loses until the number 12.

Example:

01
00
03
04
00
06
00
00
00
00
11
00

4 answers

5

I think a solution would be:

$mysql = ['01', '03', '04', '06', '11'];
$final = array_fill(0, max(12, max($mysql)), '00');

foreach($mysql as $n){
    $final[(int)$n-1] = $n;
}

var_dump($final);

Upshot:

array(12) {
  [0]=>
  string(2) "01"
  [1]=>
  string(2) "00"
  [2]=>
  string(2) "03"
  [3]=>
  string(2) "04"
  [4]=>
  string(2) "00"
  [5]=>
  string(2) "06"
  [6]=>
  string(2) "00"
  [7]=>
  string(2) "00"
  [8]=>
  string(2) "00"
  [9]=>
  string(2) "00"
  [10]=>
  string(2) "11"
  [11]=>
  string(2) "00"
}

The idea is very simple, we create with 12 values, with everything 00, using the array_fill. Then we just replace the values based on $mysql.

Like the $mysql has values in string we can’t use it directly in the array, so we passed it to int using the (int)$n. Thus the value 03 would look like $final[3] = '03'.

The max(12, max($mysql)) has been added to generate 12 values, as requested in your question However, some value of the $mysql extrapolate 12 such number shall be used. In such a situation, if $mysql = ['01', '111']; it will still work.


Although personally I would not use, there is another way, not yet used if, foreach or while explicitly:

$resultado_do_mysql = ['01', '03', '04', '06', '11'];

$final = array_replace(array_fill(1, 12, '00'), array_combine(array_map('intval', $mysql), $mysql));

var_dump($final);

What we do in this case is create another array, so we make the value go from string for int (using the array_map('intval', $mysql)). So, we use this value in int as index of the array, still keeping the original value using array_combine(array_map('intval', $mysql), $mysql). Finally, we replace the value of $final with the value of such an array, using the array_replace. I believe this is more confusing than the first method.

  • 1

    Quick hint: I would take the last number of the array (or the largest one) and add it to 1, then instead of ,12 would be the last number found, so in case mysql returns more data the code would still work.

  • 1

    @Guilhermenascimento, I added one max() so that the 12 is the minimum or the last value of the mysql, which must be the largest. The 12 is because the OP determined to be 12 even.

  • 1

    My suggestion would be to use max([01, 100]), would return 100, so what matters most is the higher value inside and not the last array item.

  • 1

    @Guilhermenascimento, It makes sense, if it is disordered it would work. I think it is now the way it spoke. : D

  • 1

    Sorry if I look boring, so this Concat you used [12] + $mysql does not work the way you believe (at least it seemed to me that the expected intention is another), for example var_dump([12] + ['01', '03', '04', '06', '11']) will trade in the value of the index = stay with the value 12, the correct would probably be to use array_merge that will merge the arrays.

  • 1

    @Guilhermenascimento, I didn’t even remember it, I haven’t used PHP in a while. :P I think in this case it would be easier to do max(12, max($mysql)), I think it’s easier to understand. If you have another mistake you can say. ;)

  • 1

    There is only one more error, your Index (index) starts on 1: array(12) {
 [1]=> - this because of your foreach, it would be better to exchange the whole foreach for simply this: $mysql = ['01', '03', '04', '06', '11']; $final = array_fill(1, max(12, max($mysql)), '00'); $final = array_values($final);, in addition to "fix" the Indice it this way will reduce the code :)

  • 1

    Didn’t you change the foreach for array_values for some reason? ps: in my view your answer is the best :) The tips I gave you were only to improve what was already good, I stand in the waiting.

  • @Guilhermenascimento, I do not know this was necessary, because the array_values would go through it all again. I think we just start from 0 and make $n-1 achieves the same goal.

  • 1

    I understood your logic, I thought it was something else, maybe I formulate an example with what I imagined and send you, hug +1

Show 5 more comments

2


One possibility to solve this is:

<?php 
$array_do_banco = array('01', '03', '04', '06', '11');
$array_saida = array();

for($i=1; $i<13; $i++){
    if(in_array($i, $array_do_banco)){
        $matches = array_keys($array_do_banco, $i);
        $array_saida[$i-1] = $array_do_banco[$matches[0]];
    }else{
        $array_saida[$i-1] = '00';
    }
}

var_dump($array_saida);
?>

The exit is:

array(12) { [0]=> string(2) "01" [1]=> string(2) "00" [2]=> string(2) "03" [3]=> string(2) "04" [4]=> string(2) "00" [5]=> string(2) "06" [6]=> string(2) "00" [7]=> string(2) "00" [8]=> string(2) "00" [9]=> string(2) "00" [10]=> string(2) "11" [11]=> string(2) "00"00" }

  • 1

    Suggestion, switch [$i-1] for [], will work the same way.

1

Friend,

You can do something in this line of code below, which I launch commented:

<?php
$numeros = array("01", "03", "04", "06", "11"); // que vieram do banco

// criamos uma função para adicionar o zero na frente do número
function zeroes($n) {
  return ((int) $n) < 10 ? "0{$n}" : "{$n}";
}

// aqui fazemos o for/loop para agregar as 12 entradas no array $resultado
$resultado = array();
for($i=1; $i<=12; $i++) {
  // usamos o in_array para saber se o teu numero existe no array original
  if(in_array($numeros, zeroes($i))) {
    // se tiver, adicionamos ele na sequencia
    $resultado[] = zeroes($i);
  } else {
    // caso não adicionamos o valor "00"
    $resultado[] = "00";
  }
}

print_r($resultado);

The basic concept here is in a loop from 1 to 12, check if the current number of the loop turn is among the numbers that came from your bank, if not, add 00 in sequence, if it is remains the original number... more or less there.

0

A more simplified example to do would be to take only the highest value and with a loop checking what exists, the logic would be to use the array coming from the database only to know how many loops will be needed by taking the maximum value obtained in the array with max(), so if it’s bigger than 12, it’ll have more than 12 cycles, if it’s smaller it’ll have exactly 12 cycles, like:

<?php
$mysql = array( '01', '03', '04', '06', '11' );

//O max dentro verifica qual o maior numero, o outro verifica se é maior ou não que 12
$max = max(12, max($mysql));

//Será o resultado final
$final = array();

//Faz um loop baseado no valor máximo
for ($i = 1; $i <= $max; $i++) {

    //Gera o valor atual
    $current = str_pad($i, 2, '0', STR_PAD_LEFT);

    //Checa se o valor atual existe no array que veio do banco
    if (in_array($current, $mysql)) {
        $final[] = $current;
    } else { //Se não existir preenche com 2 ZEROs
        $final[] = '00';
    }
}

print_r($final);

The loop starts in the 1 'cause that way it keeps us from having to do something like $i-1 within the for, example in ideone

Browser other questions tagged

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