Include numbers to complete number sequence in PHP [duplicate]

0

In this case I have the result in MYSQL.

01
03
06
09

I need to fill in the correct sequence number up to the 12th digit.

Example:

01
02
03
04
05
06
07
08
09
10
11
12
    
asked by anonymous 03.04.2018 / 15:37

2 answers

2

I do not see the need to complete, following the current need that sounds, it seems that only need 1 to 12, so using range with str_pad would already solve:

$valores = range(1, 12);

$valores = array_map(function ($item) {
    return str_pad($item, 2, '0', STR_PAD_LEFT);
}, $valores);

var_dump($valores);

Something that I think might make sense would be you search the missing numbers and return them:

function array_missing(array $arr, $min = 12)
{
    $max = max($arr);

    //Se no array tiver um valor maior que o $min
    if ($max > $min) {
       $min = $max;
    }

    $values = range(1, $min);

    $values = array_map(function ($item) {
        return str_pad($item, 2, '0', STR_PAD_LEFT);
    }, $values);

    return array_diff($values, $arr); 
}

$exemplo = array( '01', '03', '06', '09');

var_dump(array_missing($exemplo));
  

Note: $min = 12 is to set the minimum to be generated, if the array has a larger value then it will generate more items.

This will return the ones that are missing :

array(8) {
  [1]=>
  string(2) "02"
  [3]=>
  string(2) "04"
  [4]=>
  string(2) "05"
  [6]=>
  string(2) "07"
  [7]=>
  string(2) "08"
  [9]=>
  string(2) "10"
  [10]=>
  string(2) "11"
  [11]=>
  string(2) "12"
}

You can then simply merge both, for example:

$exemplo = array( '01', '03', '06', '09');

$faltam = array_missing($exemplo);

$final = array_merge($exemplo, $faltam);

sort($final); //Ordena a array

var_dump($final);
    
03.04.2018 / 15:44
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] = str_pad($i , 2 , '0' , STR_PAD_LEFT);
    }
}

var_dump($array_saida);
?>

The output is:

  

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

    
03.04.2018 / 15:47