Reorder variables by throwing the empty ones to the end

1

I want to throw the variables that are null to the end of the list. This is part of the composition of the view elements, they are blocks that can come empty, and I want to avoid having to compare variables and regroup. How can I redraw the display order of the elements on the page by throwing the empty end items?

In the example below I have the variables A, B, and C , in the normal case would make a foreach( $variavel_X as $linha ) and would have:

$variavel_A: nada aqui
$variavel_B: [ 'linha 1' , 'linha 2' , 'linha 3' ]
$variavel_C: [ 'linha 1' , 'linha 2' , 'linha 3' ]

What I need is to display as in the order below, where the empty variable appears last

$variavel_B: [ 'linha 1' , 'linha 2' , 'linha 3' ]
$variavel_C: [ 'linha 1' , 'linha 2' , 'linha 3' ]
$variavel_A: nada aqui

I thought of throwing variables in an array and reordering with arsort , but the function will do the ascending (a-z) or decreasing (z-a) order, and that does not interest me much.

    
asked by anonymous 19.06.2017 / 14:04

3 answers

1

Using only foreach could do:

foreach($array as $index => $valor){

    if(empty($valor)){
        unset($array[$index]);
        $array[$index] = $valor;
    }

}

This will check if it is empty and will remove from the array and add a new one, which will be included at the end of the array, therefore considering:

$array['a'] = [];
$array['b'] = ['linha1','linha2','linha3'];
$array['c'] = ['linha1','linha2','linha3'];
$array['d'] = null;
$array['e'] = ['linha1','linha2','linha3'];
$array['f'] = ['linha1','linha2','linha3'];
$array['g'] = '';
$array['h'] = ['linha1','linha2','linha3'];

foreach($array as $index => $valor){

    if(empty($valor)){
        unset($array[$index]);
        $array[$index] = $valor;
    }

}

Result:

array(8) {
  ["b"]=>
  array(3) {
    [0]=>
    string(6) "linha1"
    [1]=>
    string(6) "linha2"
    [2]=>
    string(6) "linha3"
  }
  ["c"]=>
  array(3) {
    [0]=>
    string(6) "linha1"
    [1]=>
    string(6) "linha2"
    [2]=>
    string(6) "linha3"
  }
  ["e"]=>
  array(3) {
    [0]=>
    string(6) "linha1"
    [1]=>
    string(6) "linha2"
    [2]=>
    string(6) "linha3"
  }
  ["f"]=>
  array(3) {
    [0]=>
    string(6) "linha1"
    [1]=>
    string(6) "linha2"
    [2]=>
    string(6) "linha3"
  }
  ["h"]=>
  array(3) {
    [0]=>
    string(6) "linha1"
    [1]=>
    string(6) "linha2"
    [2]=>
    string(6) "linha3"
  }
  ["a"]=>
  array(0) {
  }
  ["d"]=>
  NULL
  ["g"]=>
  string(0) ""
}

Test this.

    
19.06.2017 / 17:57
2

There are many ordering algorithms to solve your case.

But let's go to the classic Bubble Sort

How it works:

This algorithm traverses the list of orderable items from beginning to end, checking the order of the elements two by two, and swapping them out of place if necessary. You scroll through the list until nothing has been changed in the previous passage.

So let's say you're using a two-dimensional array:

$arr = array();
$arr['a'] = array();
$arr['b'] = array('linha1','linha2','linha3');
$arr['c'] = array('linha1','linha2','linha3');
$arr['d'] = array();
$arr['e'] = array('linha1','linha2','linha3');
$arr['f'] = array('linha1','linha2','linha3');
$arr['g'] = array();
$arr['h'] = array('linha1','linha2','linha3');

By creating this code below, you are checking each item to place the empty arrays last:

function bubble_sort(&$array){

        $tam = count($array);

        reset($array);//Aponta para primeira posição

        for($i = 0; $i<$tam; $i++){
            for($j = 0; $j<($tam-1); $j++){             
                //Pega dados da posição atual
                $current_position = each($array);
                //Pega dados da proxima posição
                $next_position = each($array);
                prev($array); //Volta posição   

                if(empty($current_position['value']) &&
                   !empty($next_position['value'])){              
                    $array[$current_position['key']] = $next_position['value'];
                    $array[$next_position['key']] = $current_position['value'];                                 
                }

            }
            reset($array);//Aponta para primeira posição
        }

    }

    bubble_sort($arr);

    echo json_encode($arr);

Entry:

  

{"a": [], "b": ["line1", "line2", "line3"], "c": ["line1", "line2" : [], "h": [], "e": [], "e": [ : ["line1", "line2", "line3"]}

Output:

  

{"a": ["line1", "line2", "line3"], "b": ["line1", "line2", "line3"], line2 "," line3 "]," d ": [" line1 "," line2 "," line3 "]," e ": [ , "g": [], "h": []}

    
19.06.2017 / 15:56
2
  

uasort - Sorts an array using a function user-defined comparison and maintaining the associations between keys and values.

See an example of how to use based on your question:

<?php

// Definição dos arrays
$arr = array();
$arr['a'] = array();
$arr['b'] = array('linha1','linha2','linha3', 'linha4');
$arr['c'] = array('linha1','linha2','linha3');
$arr['d'] = array();
$arr['e'] = array('linha1','linha2','linha3');
$arr['f'] = array('linha1','linha2','linha3');
$arr['g'] = array();
$arr['h'] = array('linha1','linha2','linha3');

// Função personalizada para ordenar os arrays
// 0 quer dizer igual, -1 joga para o início e 1 para o final.
function sortArrays($a, $b) {
    
    if(count($a) == count($b)){
    	return 0;
    }

    return (count($a) > count($b)) ? -1 : 1;
}

// Reordena os arrays
uasort($arr, 'sortArrays');

// Imprime o array ordenado
print_r($arr);

?>

Final result:

Array
(
    [b] => Array
        (
            [0] => linha1
            [1] => linha2
            [2] => linha3
            [3] => linha4
        )

    [c] => Array
        (
            [0] => linha1
            [1] => linha2
            [2] => linha3
        )

    [e] => Array
        (
            [0] => linha1
            [1] => linha2
            [2] => linha3
        )

    [f] => Array
        (
            [0] => linha1
            [1] => linha2
            [2] => linha3
        )

    [h] => Array
        (
            [0] => linha1
            [1] => linha2
            [2] => linha3
        )

    [a] => Array
        (
        )

    [d] => Array
        (
        )

    [g] => Array
        (
        )

)
    
19.06.2017 / 17:15