function regerar_rank()
{
    $bd = new bd();
    //        $var  = "ESPVIDA;FECTOT;MORT1;MORT5;RAZDEP;SOBRE40;SOBRE60;T_ENV;E_ANOSESTUDO;T_ANALF11A14;T_ANALF15A17;T_ANALF15M;T_ANALF18A24;T_ANALF18M;T_ANALF25A29;T_ANALF25M;T_ATRASO_0_BASICO;T_ATRASO_0_FUND;T_ATRASO_0_MED;T_ATRASO_1_BASICO;T_ATRASO_1_FUND;T_ATRASO_1_MED;T_ATRASO_2_BASICO;T_ATRASO_2_FUND;T_ATRASO_2_MED;T_FBBAS;T_FBFUND;T_FBMED;T_FBPRE;T_FBSUPER;T_FLBAS;T_FLFUND;T_FLMED;T_FLPRE;T_FLSUPER;T_FREQ0A3;T_FREQ11A14;T_FREQ15A17;T_FREQ18A24;T_FREQ25A29;T_FREQ4A5;T_FREQ4A6;T_FREQ5A6;T_FREQ6;T_FREQ6A14;T_FREQ6A17;T_FREQFUND1517;T_FREQFUND1824;T_FREQFUND45;T_FREQMED1824;T_FREQMED614;T_FREQSUPER1517;T_FUND11A13;T_FUND12A14;T_FUND15A17;T_FUND16A18;T_FUND18A24;T_FUND18M;T_FUND25M;T_MED18A20;T_MED18A24;T_MED18M;T_MED19A21;T_MED25M;T_SUPER25M;CORTE1;CORTE2;CORTE3;CORTE4;CORTE9;GINI;PIND;PINDCRI;PMPOB;PMPOBCRI;PPOB;PPOBCRI;PREN10RICOS;PREN20;PREN20RICOS;PREN40;PREN60;PREN80;PRENTRAB;R1040;R2040;RDPC;RDPC1;RDPC10;RDPC2;RDPC3;RDPC4;RDPC5;RDPCT;RIND;RMPOB;RPOB;THEIL;CPR;EMP;P_AGRO;P_COM;P_CONSTR;P_EXTR;P_FORMAL;P_FUND;P_MED;P_SERV;P_SIUP;P_SUPER;P_TRANSF;REN0;REN1;REN2;REN3;REN5;RENOCUP;T_ATIV;T_ATIV1014;T_ATIV1517;T_ATIV1824;T_ATIV18M;T_ATIV2529;T_DES;T_DES1014;T_DES1517;T_DES1824;T_DES18M;T_DES2529;THEILtrab;TRABCC;TRABPUB;TRABSC;T_AGUA;T_BANAGUA;T_DENS;T_LIXO;T_LUZ;AGUA_ESGOTO;PAREDE;T_CRIFUNDIN_TODOS;T_FORA4A5;T_FORA6A14;T_FUNDIN_TODOS;T_FUNDIN_TODOS_MMEIO;T_FUNDIN18MINF;T_M10A14CF;T_M15A17CF;T_MULCHEFEFIF014;T_NESTUDA_NTRAB_MMEIO;T_OCUPDESLOC_1;T_RMAXIDOSO;T_SLUZ;HOMEM0A4;HOMEM10A14;HOMEM15A19;HOMEM20A24;HOMEM25A29;HOMEM30A34;HOMEM35A39;HOMEM40A44;HOMEM45A49;HOMEM50A54;HOMEM55A59;HOMEM5A9;HOMEM60A64;HOMEM65A69;HOMEM70A74;HOMEM75A79;HOMEMTOT;HOMENS80;MULH0A4;MULH10A14;MULH15A19;MULH20A24;MULH25A29;MULH30A34;MULH35A39;MULH40A44;MULH45A49;MULH50A54;MULH55A59;MULH5A9;MULH60A64;MULH65A69;MULH70A74;MULH75A79;MULHER80;MULHERTOT;PEA;PEA1014;PEA1517;PEA18M;peso1;PESO1114;PESO1113;PESO1214;peso13;PESO15;peso1517;PESO1524;PESO1618;PESO18;Peso1820;PESO1824;Peso1921;PESO25;peso4;peso5;peso6;PESO610;Peso617;PESO65;PESOM1014;PESOM1517;PESOM15M;PESOM25M;pesoRUR;pesotot;pesourb;PIA;PIA1014;PIA1517;PIA18M;POP;POPT;I_ESCOLARIDADE;I_FREQ_PROP;IDHM;IDHM_E;IDHM_L;IDHM_R";
    //
    //
    //        $ex = explode(';',$var);
    //
    //        $result = array();
    //
    //        foreach($ex as $v){
    //            $v = trim($v);
    //            $sql = "select id from variavel where sigla ILIKE '$v'";
    //            $arr = $bd->ExecutarSQL($sql);
    //            echo $arr[0]['id'].",$v<br />";
    //        }
    //        $result = array();
    //        foreach($ex as $v){
    //            $v = trim($v);
    //            $sql = "select id from municipio where substring(geocodmun::text from 0 for 7) = '$v'";
    //            $arr = $bd->ExecutarSQL($sql);
    //            if(count($arr) > 1){
    //                die("ERROOOOOOOOOO: $v");
    //            }
    //            if($c > 10) die();
    //            echo $arr[0]['id']."<br />";
    //            $result[] = $arr[0]["id"];
    //            $c++;
    //        }
    //        $lines = file("config/rank_save.csv");
    //        $insert = array();
    //        $sql = "INSERT INTO rank(fk_municipio,posicao_idh,posicao_e_idh,posicao_idhe,posicao_e_idhe,posicao_idhr,posicao_e_idhr,posicao_idhl,posicao_e_idhl) VALUES ";
    //        foreach($lines as $linha){
    //            $insert[] = "(".implode(',',explode(';', $linha)).")";
    //        }
    //        $sql .= implode(',', $insert);
    //        $bd->insert($sql);
    //        die($sql);
    die;
    return;
    $bd = new bd();
    $ALL = array();
    $bd->insert("TRUNCATE TABLE rank");
    $SQL1 = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                                  WHERE fk_variavel IN (196) and fk_ano_referencia = 3 ORDER BY valor_variavel_mun.valor desc";
    $SQLR = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                                  WHERE fk_variavel IN (197) and fk_ano_referencia = 3 ORDER BY valor_variavel_mun.valor desc";
    $SQLL = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                                  WHERE fk_variavel IN (198) and fk_ano_referencia = 3 ORDER BY valor_variavel_mun.valor desc";
    $SQLE = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                                  WHERE fk_variavel IN (199) and fk_ano_referencia = 3 ORDER BY valor_variavel_mun.valor desc";
    $arr = $bd->ExecutarSQL($SQL1);
    $last = "";
    $posicao = 0;
    foreach ($arr as $key => $v) {
        $v["valor"] = cutNumber($v["valor"], 3, ',', '');
        if ($last != $v["valor"]) {
            $posicao++;
        }
        $last = $v["valor"];
        $ALL[$v["fk_municipio"]][$v["fk_variavel"]] = $posicao;
    }
    $arr = $bd->ExecutarSQL($SQLR);
    $last = "";
    $posicao = 0;
    foreach ($arr as $key => $v) {
        $v["valor"] = cutNumber($v["valor"], 3, ',', '');
        if ($last != $v["valor"]) {
            $posicao++;
        }
        $last = $v["valor"];
        $ALL[$v["fk_municipio"]][$v["fk_variavel"]] = $posicao;
    }
    $arr = $bd->ExecutarSQL($SQLL);
    $last = "";
    $posicao = 0;
    foreach ($arr as $key => $v) {
        $v["valor"] = cutNumber($v["valor"], 3, ',', '');
        if ($last != $v["valor"]) {
            $posicao++;
        }
        $last = $v["valor"];
        $ALL[$v["fk_municipio"]][$v["fk_variavel"]] = $posicao;
    }
    $arr = $bd->ExecutarSQL($SQLE);
    $last = "";
    $posicao = 0;
    foreach ($arr as $key => $v) {
        $v["valor"] = cutNumber($v["valor"], 3, ',', '');
        if ($last != $v["valor"]) {
            $posicao++;
        }
        $last = $v["valor"];
        $ALL[$v["fk_municipio"]][$v["fk_variavel"]] = $posicao;
    }
    for ($i = 1; $i <= 27; $i++) {
        $SQL = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                        INNER JOIN municipio as m ON (fk_municipio = m.id)\n                        WHERE fk_variavel IN (196) and fk_ano_referencia = 3 AND m.fk_estado = {$i} order by valor";
        $arr = $bd->ExecutarSQL($SQL);
        $last = "";
        $posicao = 0;
        foreach ($arr as $key => $v) {
            $v["valor"] = cutNumber($v["valor"], 3, ',', '');
            if ($last != $v["valor"]) {
                $posicao++;
            }
            $last = $v["valor"];
            $ALL[$v["fk_municipio"]][$v["fk_variavel"] . "e"] = $posicao;
        }
        $SQL = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                        INNER JOIN municipio as m ON (fk_municipio = m.id)\n                        WHERE fk_variavel IN (197) and fk_ano_referencia = 3 AND m.fk_estado = {$i} order by valor";
        $arr = $bd->ExecutarSQL($SQL);
        $last = "";
        $posicao = 0;
        foreach ($arr as $key => $v) {
            $v["valor"] = cutNumber($v["valor"], 3, ',', '');
            if ($last != $v["valor"]) {
                $posicao++;
            }
            $last = $v["valor"];
            $ALL[$v["fk_municipio"]][$v["fk_variavel"] . "e"] = $posicao;
        }
        $SQL = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                        INNER JOIN municipio as m ON (fk_municipio = m.id)\n                        WHERE fk_variavel IN (198) and fk_ano_referencia = 3 AND m.fk_estado = {$i} order by valor";
        $arr = $bd->ExecutarSQL($SQL);
        $last = "";
        $posicao = 0;
        foreach ($arr as $key => $v) {
            $v["valor"] = cutNumber($v["valor"], 3, ',', '');
            if ($last != $v["valor"]) {
                $posicao++;
            }
            $last = $v["valor"];
            $ALL[$v["fk_municipio"]][$v["fk_variavel"] . "e"] = $posicao;
        }
        $SQL = "SELECT fk_municipio,valor,fk_variavel FROM valor_variavel_mun\n                        INNER JOIN municipio as m ON (fk_municipio = m.id)\n                        WHERE fk_variavel IN (199) and fk_ano_referencia = 3 AND m.fk_estado = {$i} order by valor";
        $arr = $bd->ExecutarSQL($SQL);
        $last = "";
        $posicao = 0;
        foreach ($arr as $key => $v) {
            $v["valor"] = cutNumber($v["valor"], 3, ',', '');
            if ($last != $v["valor"]) {
                $posicao++;
            }
            $last = $v["valor"];
            $ALL[$v["fk_municipio"]][$v["fk_variavel"] . "e"] = $posicao;
        }
        echo $i . "<br />";
    }
    $SQL2 = array();
    foreach ($ALL as $key => $v) {
        $SQL2[] = "({$key},{$v[196]},{$v[197]},{$v[198]},{$v[199]},{$v["196e"]},{$v["197e"]},{$v["198e"]},{$v["199e"]})";
    }
    $s = join(",", $SQL2);
    $SQL = "INSERT INTO rank(fk_municipio,posicao_idh,posicao_idhr,posicao_idhl,posicao_idhe,posicao_e_idh,posicao_e_idhr,posicao_e_idhl,posicao_e_idhe) values {$s}";
    die($SQL);
    //$bd->insert($SQL);
    //header("location: ../admin");
}
 /**
  * Pega o retorno do SQL
  * @param string $SQL recebe a sql e executa
  * @example <br />array(1) {
  *   <br />[2365]=>
  *   <br />array(2) {
  *     <br />["nome"]=>
  *     <br />string(19) "ABADIA DOS DOURADOS"
  *     <br />[0]=>
  *     <br />array(3) {
  *       <br />["valor"]=>
  *       <br />string(6) "72.936"
  *       <br />["fk_ano_referencia"]=>
  *       <br />string(1) "3"
  *       <br />["fk_variavel"]=>
  *       <br />string(1) "1"
  *     <br />}
  *   <br />}
  */
 private function iRunSQLSecundarioCC($ResultadosMain, $SQL)
 {
     //die($SQL);
     if (strpos($SQL, "()")) {
         die(json_encode(array("erro" => 1, "msg" => " Houve um erro desconhecido no servidor, recarregue a página. <br />Código: #001")));
     }
     $tempArry = parent::ExecutarSQL($SQL, "iRunSQLSecundario22");
     //die(var_dump($tempArry));
     $dv = 0;
     $Formatado = array();
     foreach ($tempArry as $key => $val) {
         if ($val['country'] === 'true') {
             //Paises
             //$Formatado[]=$val['nome'];
             $this->varOnly = false;
             if (!$this->varOnly) {
                 $arg = $val;
                 //die(var_dump($arg));
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['country']);
                 unset($arg['rm']);
                 unset($arg['u']);
                 unset($arg['uf']);
                 unset($arg['udh']);
                 unset($arg['is_ri']);
                 unset($arg['reg']);
                 unset($arg['cod']);
                 unset($val['rm']);
                 unset($val['u']);
                 unset($val['uf']);
                 unset($val['udh']);
                 unset($val['is_ri']);
                 unset($val['reg']);
                 unset($val['cod']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName)
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 $Formatado[$val['im']]["country"] = $val["country"];
                 $Formatado[$val['im']]["id"] = str_replace("10000", "", $val["im"]);
                 $Formatado[$val['im']]["esp"] = 10;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $val["v"] = cutNumber($val["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $val["v"] = cutNumber($val["v"], 2, '.', '');
                 } else {
                     $val["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 $Formatado[$key] = $val;
             }
         } elseif ($val['rm'] === 'true') {
             //RMs
             //$Formatado[]=$val['nome'];
             if (!$this->varOnly) {
                 $arg = $val;
                 //die(var_dump($arg));
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['rm']);
                 unset($arg['country']);
                 unset($arg['u']);
                 unset($arg['uf']);
                 unset($arg['udh']);
                 unset($arg['is_ri']);
                 unset($arg['reg']);
                 unset($arg['cod']);
                 unset($val['country']);
                 unset($val['u']);
                 unset($val['uf']);
                 unset($val['udh']);
                 unset($val['is_ri']);
                 unset($val['reg']);
                 unset($val['cod']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName)
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 //$Formatado[$val['im']]["u"] = $val["u"];
                 $Formatado[$val['im']]["rm"] = $val["rm"];
                 $Formatado[$val['im']]["id"] = str_replace("10000", "", $val["im"]);
                 $Formatado[$val['im']]["esp"] = 6;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 foreach ($tempArry as $key => $val) {
                     if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 3, '.', '');
                     } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 2, '.', '');
                     } else {
                         $val["v"] = cutNumber($arg["v"], 2, '.', '');
                     }
                     $Formatado[$key] = $val;
                 }
             }
         } elseif ($val['reg'] === 'true') {
             //Regional
             //$Formatado[]=$val['nome'];
             if (!$this->varOnly) {
                 $arg = $val;
                 //die(var_dump($arg));
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['reg']);
                 unset($arg['country']);
                 unset($arg['u']);
                 unset($arg['uf']);
                 unset($arg['rm']);
                 unset($arg['udh']);
                 unset($arg['is_ri']);
                 unset($arg['cod']);
                 unset($val['country']);
                 unset($val['u']);
                 unset($val['uf']);
                 unset($val['rm']);
                 unset($val['udh']);
                 unset($val['is_ri']);
                 unset($val['cod']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName)
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 //$Formatado[$val['im']]["u"] = $val["u"];
                 $Formatado[$val['im']]["reg"] = $val["reg"];
                 $Formatado[$val['im']]["id"] = str_replace("10000", "", $val["im"]);
                 $Formatado[$val['im']]["esp"] = 3;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 foreach ($tempArry as $key => $val) {
                     if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 3, '.', '');
                     } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 2, '.', '');
                     } else {
                         $val["v"] = cutNumber($arg["v"], 2, '.', '');
                     }
                     $Formatado[$key] = $val;
                 }
             }
         } elseif ($val['udh'] === 'true') {
             //UHDs
             //$Formatado[]=$val['nome'];
             if (!$this->varOnly) {
                 $arg = $val;
                 //die(var_dump($arg));
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['udh']);
                 unset($arg['country']);
                 unset($arg['u']);
                 unset($arg['uf']);
                 unset($arg['rm']);
                 unset($arg['is_ri']);
                 unset($arg['reg']);
                 unset($arg['cod']);
                 unset($val['country']);
                 unset($val['u']);
                 unset($val['uf']);
                 unset($val['rm']);
                 unset($val['is_ri']);
                 unset($val['reg']);
                 unset($val['cod']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName)
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 //$Formatado[$val['im']]["u"] = $val["u"];
                 $Formatado[$val['im']]["udh"] = $val["udh"];
                 $Formatado[$val['im']]["id"] = str_replace("10000", "", $val["im"]);
                 $Formatado[$val['im']]["esp"] = 5;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 foreach ($tempArry as $key => $val) {
                     if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 3, '.', '');
                     } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 2, '.', '');
                     } else {
                         $val["v"] = cutNumber($arg["v"], 2, '.', '');
                     }
                     $Formatado[$key] = $val;
                 }
             }
         } elseif (strlen($val['u']) and !strlen($val['uf'])) {
             //Estatual
             if (!$this->varOnly) {
                 $arg = $val;
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['u']);
                 unset($arg['cod']);
                 unset($arg['country']);
                 unset($arg['rm']);
                 unset($arg['uf']);
                 unset($arg['udh']);
                 unset($arg['is_ri']);
                 unset($arg['reg']);
                 unset($val['country']);
                 unset($val['rm']);
                 unset($val['uf']);
                 unset($val['udh']);
                 unset($val['is_ri']);
                 unset($val['reg']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName)
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 $Formatado[$val['im']]["u"] = $val["u"];
                 $Formatado[$val['im']]["cod"] = $val["cod"];
                 $Formatado[$val['im']]["id"] = str_replace("10000", "", $val["im"]);
                 $Formatado[$val['im']]["esp"] = 4;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $val["v"] = cutNumber($val["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $val["v"] = cutNumber($val["v"], 2, '.', '');
                 } else {
                     $val["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 $Formatado[$key] = $val;
             }
         } elseif (strlen($val['u']) and strlen($val['uf'])) {
             //Municipal
             //$Formatado[]=$val['nome'];
             if (!$this->varOnly) {
                 //$dv++;
                 $arg = $val;
                 unset($arg['im']);
                 unset($arg['nome']);
                 unset($arg['uf']);
                 unset($arg['cod']);
                 unset($arg['country']);
                 unset($arg['rm']);
                 unset($arg['u']);
                 unset($arg['udh']);
                 unset($arg['is_ri']);
                 unset($arg['reg']);
                 unset($val['country']);
                 unset($val['rm']);
                 unset($val['u']);
                 unset($val['udh']);
                 unset($val['is_ri']);
                 unset($val['reg']);
                 if (in_array($arg["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 3, '.', '');
                 } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 } else {
                     $arg["v"] = cutNumber($arg["v"], 2, '.', '');
                 }
                 //if($this->isSearchName){
                 //if(isset($val["nome"]))
                 $Formatado[$val['im']]["nome"] = $val["nome"];
                 if (isset($val["uf"])) {
                     $Formatado[$val['im']]["uf"] = $val["uf"];
                 }
                 //}
                 $Formatado[$val['im']]["cod"] = $val["cod"];
                 $Formatado[$val['im']]["id"] = $val["im"];
                 $Formatado[$val['im']]["esp"] = 2;
                 $Formatado[$val['im']]["vs"][$val["iv"] . "_" . $val["ka"]] = $arg;
             } else {
                 foreach ($tempArry as $key => $val) {
                     if (in_array($val["iv"], PublicMethods::$ArrayPadding3ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 3, '.', '');
                     } elseif (in_array($val["iv"], PublicMethods::$ArrayPadding2ZerosDireita)) {
                         $val["v"] = cutNumber($val["v"], 2, '.', '');
                     } else {
                         $val["v"] = cutNumber($arg["v"], 2, '.', '');
                     }
                     $Formatado[$key] = $val;
                 }
             }
         }
     }
     //die(var_dump($Formatado));
     //die(var_dump($dv));
     $this->results = $Formatado;
 }
 private function read()
 {
     $SQL = "SELECT municipio.nome, uf, municipio.id, estado.nome as nomeestado, (ST_AsGeoJSON(municipio.the_geom)) as locale FROM municipio \n                    INNER JOIN estado ON (municipio.fk_estado = estado.id)\n                    WHERE sem_acento(municipio.nome) ILIKE '{$this->UrlNome}' AND (uf ILIKE '{$this->ufCru}' OR sem_acento(estado.nome) ILIKE '{$this->UrlUf}') LIMIT 1";
     $results = parent::ExecutarSQL($SQL);
     if (sizeof($results) > 0) {
         $this->nome = $results[0]["nome"];
         $this->uf = $results[0]["uf"];
         $this->id = $results[0]["id"];
         $this->estado = $results[0]["nomeestado"];
         $this->locale = $results[0]["locale"];
     }
 }
        break;
    case TABELA_REGIAO:
        $SQL1 = "SELECT nome,id FROM regiao\n                 WHERE sem_acento(nome) ILIKE '{$stringTratada}%' ORDER BY nome LIMIT 9";
        break;
    case TABELA_UDH:
        $SQL1 = "SELECT udh.nome,estado.uf, udh.id FROM udh\n                 INNER JOIN municipio ON (municipio.id = udh.fk_municipio)\n                 INNER JOIN estado ON (estado.id = municipio.fk_estado)\n                 WHERE sem_acento(udh.nome) ILIKE '{$stringTratada}%' ORDER BY udh.nome LIMIT 9";
        break;
    case TABELA_MUNICIPIO_ESTADO:
        $SQL1 = "SELECT municipio.nome,estado.uf,municipio.id FROM municipio\n                 INNER JOIN estado ON (estado.id = municipio.fk_estado)\n                 WHERE sem_acento(municipio.nome) ILIKE '{$stringTratada}%' ORDER BY municipio.nome LIMIT 9";
        //             $SQL2 = "SELECT nome,estado.uf,id FROM estado
        //                 WHERE sem_acento(nome) ILIKE '$stringTratada%' ORDER BY nome LIMIT 10";
        break;
}
$Resultante = array();
$ArrayId = array();
$result = $db->ExecutarSQL($SQL1);
foreach ($result as $key) {
    $ArrayId[] = $key['id'];
    $Resultante[] = array('nome' => $key['nome'], 'uf' => $key['uf'], 'id' => $key['id']);
}
$c = 10 - count($result);
if ($c > 0) {
    if (count($ArrayId) > 0) {
        $conjunto = implode(',', $ArrayId);
    } else {
        $conjunto = 0;
    }
    switch ($tabela) {
        case TABELA_MUNICIPIO:
            $SQL2 = "SELECT municipio.nome,estado.uf,municipio.id FROM municipio\n                         INNER JOIN estado ON (estado.id = municipio.fk_estado)\n                         WHERE sem_acento(municipio.nome) ILIKE '%{$stringTratada}%' and municipio.id not in ({$conjunto}) ORDER BY municipio.nome LIMIT {$c}";
            break;
 /**
  * Executa um sql pela classe bd.class.php
  * 
  * @param string $SQL SQL de consulta
  * @return Array
  */
 public function bdExecutarSQL($SQL, $ident = "|source não definida|")
 {
     return parent::ExecutarSQL($SQL, $ident);
 }
 private function readUDH()
 {
     $SQL = "SELECT udh.nome, uf, municipio.nome as nome_mun, rm.nome as nome_rm, municipio.fk_rm as rmid, udh.id, estado.nome as nomeestado,\n            (ST_AsGeoJSON(udh.the_geom)) as locale FROM udh\n                    INNER JOIN municipio ON (municipio.id = udh.fk_municipio)\n                 INNER JOIN estado ON (estado.id = municipio.fk_estado)\n                                     INNER JOIN rm ON (rm.id = udh.fk_rm)\n                    WHERE ( sem_acento(udh.nome) ILIKE '{$this->UrlNome}' AND\n                        (uf ILIKE '{$this->ufCru}' OR sem_acento(estado.nome) ILIKE '{$this->UrlUf}') ) OR " . " udh.id = {$this->UrlCod} OR" . " udh.cod_udhatlas ILIKE '{$this->UrlCod}' LIMIT 1";
     if ($this->UrlCod != null || $this->UrlCod == 0) {
         $results = parent::ExecutarSQL($SQL);
         if (sizeof($results) > 0) {
             $this->nome = $results[0]["nome"];
             $this->uf = $results[0]["uf"];
             $this->id = $results[0]["id"];
             $this->estado = $results[0]["nomeestado"];
             $this->locale = $results[0]["locale"];
             $this->nome_mun = $results[0]["nome_mun"];
             $this->nome_rm = $results[0]["nome_rm"];
         }
     }
 }
 public function __construct($ordem_id = null, $ordem = null, $pag = null, $espc = null, $start = null, $estado = null, $estados_pos = null, $load_more = false, $download = false, $ano = 3, $lang = null)
 {
     $limit = 100;
     if ($lang != null) {
         //Se $lang for diferente de null
         $this->lang = $lang;
     } else {
         if (get_class($ordem_id) == "LangManager") {
             //Se a classe de $ordem_id for igual a LangManager
             $this->lang = $ordem_id;
             $ordem_id = null;
         }
     }
     $this->showBtn = $load_more;
     if ($load_more) {
         $limit = 12000;
     }
     if (is_null($ordem_id)) {
         //Se $ordem_id for null
         $ordem_id = INDICADOR_IDH;
         //INDICADOR_IDH é igual a 196
     }
     if (is_null($ordem)) {
         //Se $ordem for igual a null
         $ordem = "asc";
         //$ordem será igual a asc
     }
     if (is_null($limit)) {
         //Se $lmiti for igual a null
         $limit = 100;
     }
     if (is_null($espc)) {
         //Se $espc for igual a null
         $espc = "municipal";
     }
     if (is_null($pag)) {
         //Se $pag for igual a null
         $pag = 1;
     }
     if (is_null($start) || $start < 0) {
         $start = 1;
     }
     if (is_null($estado)) {
         $estado = 0;
     }
     if ($ordem != "desc" && $ordem != "asc") {
         $ordem = "asc";
     }
     $this->fkAno = (int) $ano;
     if ($this->fkAno == 0) {
         $this->fkAno = 3;
     }
     if (($espc == 'udh' || $espc == 'rm') && $this->fkAno == 1) {
         //Para rm e udh o ano será somente 2010
         $this->fkAno = 3;
     }
     $this->pOrdem_id = (int) $ordem_id;
     $this->pOrdem = $ordem;
     $this->pLimit = (int) $limit;
     $this->pEspc = $espc;
     $this->pPag = (int) $pag;
     $this->pStart = (int) $start;
     $this->pEstado = (int) $estado;
     $bd = new bd();
     $rankingBy = "";
     //Colunas do Ranking. Os Cases indicam a primeira coluna
     switch ($ordem_id) {
         case INDICADOR_IDH:
             //Coluna IDHM
             $this->nOrdem = $this->lang->getString("rankin_idhm");
             //Nome da Coluna
             $rankingBy = "posicao_idh";
             break;
         case INDICADOR_RENDA:
             //Coluna IDHM RENDA
             $this->nOrdem = $this->lang->getString("rankin_renda2");
             $rankingBy = "posicao_idhr";
             break;
         case INDICADOR_LONGEVIDADE:
             //Coluna IDHM LONGEVIDADE
             $this->nOrdem = $this->lang->getString("rankin_Long");
             $rankingBy = "posicao_idhl";
             break;
         case INDICADOR_EDUCACAO:
             //Coluna IDHM EDUCAÇÃO
             $this->nOrdem = $this->lang->getString("rankin_edu");
             $rankingBy = "posicao_idhe";
             break;
         default:
             break;
     }
     //        echo $this->fkAno;
     //Dentro de $this->sql_proto[$espc], onde tiver VARS, substitui pelo valor de $ordem_id
     $sql_seletor = str_replace("VARS", $ordem_id, $this->sql_proto[$espc]) . " ORDER BY ot {$ordem} LIMIT {$limit} offset " . ($pag - 1) * $limit;
     //Dentro de $sql_seletor, onde tiver (ANO), substitui pelo valor de $this->fkAno
     $sql_seletor = str_replace("(ANO)", $this->fkAno, $sql_seletor);
     if ($this->pEstado > 0 && $espc == "municipal") {
         $sql_seletor = str_replace("(MOREWHERE)", " AND e.id = {$this->pEstado} ", $sql_seletor);
         $rankingBy = str_replace("_", "_e_", $rankingBy);
     } else {
         if ($this->pEstado > 0 && $espc == "udh") {
             $sql_seletor = str_replace("(MOREWHERE)", " AND e.id = {$this->pEstado} ", $sql_seletor);
             $rankingBy = str_replace("_", "_r_", $rankingBy);
         } else {
             //Dentro de $sql_seletor, onde tiver (MOREWHERE), substituir por ""(vazio)
             $sql_seletor = str_replace("(MOREWHERE)", "", $sql_seletor);
         }
     }
     $sql_seletor = str_replace("(TBS)", ",{$rankingBy} as ot", $sql_seletor);
     $res = $bd->ExecutarSQL($sql_seletor, "frist");
     $ids = array();
     if ($espc == "municipal") {
         //Se a espacialidade for igual a 'municipal'
         foreach ($res as $key => $val) {
             $this->municipio = array("mun" => "{$val["n"]}", "uf" => "{$val["uf"]}");
             $this->data[$val["i"]] = array("mun" => "{$val["n"]}", "uf" => "{$val["uf"]}", "n" => "{$val["n"]} ({$val["uf"]})", "ot" => $val["ot"], "vs" => array($ordem_id => array("v" => $val["v"], "k" => $ordem_id)));
             $ids[] = $val["i"];
             //Salva no array $ids as chaves de município
         }
         $SQL_e = "SELECT nome, id FROM estado order by nome";
         //Retorna os nomes dos estados
         $resp = $bd->ExecutarSQL($SQL_e, "estado 22");
         $this->estados = $resp;
     } else {
         if ($espc == "udh") {
             //Se a espacialidade for igual a 'udh'
             foreach ($res as $key => $val) {
                 $this->data[$val["i"]] = array("udh" => "{$val["n"]}", "mun" => "{$val["nrm"]}", "idgeo" => "{$val['idgeo']}", "n" => "{$val["n"]} ({$val["nrm"]})", "ot" => $val["ot"], "vs" => array($ordem_id => array("v" => $val["v"], "k" => $ordem_id)));
                 $ids[] = $val["i"];
                 //Salva no array $ids as chaves de município
             }
             $SQL_e = "SELECT nome, id FROM rm WHERE ativo = TRUE order by nome";
             //Retorna os nomes dos estados
             $resp = $bd->ExecutarSQL($SQL_e, "ranking 16");
             $this->estados = $resp;
         } else {
             if ($espc == "estadual" || $espc == 'rm') {
                 //Se a espacialidade for estadual
                 $counter = 0;
                 $last = 0;
                 $hidden_array = array();
                 $arr = explode(",", $estados_pos);
                 $t = count($arr) - 1;
                 foreach ($res as $key => $val) {
                     if ($ordem == "desc") {
                         if ($last != cutNumber($val["v"], 3, '.')) {
                             $counter++;
                         }
                         $last = cutNumber($val["v"], 3, '.');
                     }
                     if ($ordem == "asc") {
                         $counter = $arr[$t];
                         if ($t != 0) {
                             $t--;
                         }
                     }
                     $hidden_array[] = $counter;
                     $val_at = isset($val['at']) ? $val['at'] : '';
                     $this->data[$val["i"]] = array("ot" => $val["ot"], "n" => "{$val["n"]}", "ativo" => "{$val_at}", "vs" => array($ordem_id => array("v" => $val["v"], "k" => $ordem_id)));
                     $ids[] = $val["i"];
                 }
                 echo "<input type='hidden' value='" . join(",", $hidden_array) . "' id='holderRankEstados' />";
             }
         }
     }
     $places = implode(",", $ids);
     //Separa cada id de município por uma vírgula
     $vars = implode(",", array_diff($this->id_indics, array($ordem_id)));
     //Retorna a diferença entre os arrays
     $var_name = "";
     if ($espc == "municipal") {
         $var_name = "fk_municipio";
     } elseif ($espc == "estadual") {
         $var_name = "fk_estado";
     } else {
         if ($espc == 'rm') {
             $var_name = 'fk_rm';
         } else {
             if ($espc == 'udh') {
                 $var_name = 'fk_udh';
             }
         }
     }
     //Dentro de $this->sql_f[$espc], onde tiver (ANO), substitui pelo valor de $this->fkAno
     $this->sql_f[$espc] = str_replace("(ANO)", $this->fkAno, $this->sql_f[$espc]);
     //Dentro de $this->sql_f[$espc]) . " and $var_name IN ($places) order by fk_variavel, onde tiver VARS, substitui pelo valor de $vars
     //Valores das outras 3 colunas do ranking
     $sql_follower = str_replace("VARS", $vars, $this->sql_f[$espc]) . " and {$var_name} IN ({$places}) order by fk_variavel";
     $res_f = $bd->ExecutarSQL($sql_follower);
     foreach ($res_f as $key => $val) {
         $this->data[$val["i"]]["vs"][$val["k"]] = array("v" => $val["v"], "k" => $val["k"]);
     }
     if ($download) {
         ob_end_clean();
         //Encerro o segundo buffer de saída da pilha e jogo conteúdo fora
         ob_clean();
         // Limpo o primeiro buffer de saída
         /*echo "\t";*/
         $n = $this->getNomeIndicador($ordem_id);
         $n = str_replace(" ", "_", $n);
         if ($espc == "municipal") {
             if ($estado == 0) {
                 download_send_headers("AtlasIDHM_RankingMunicipal_" . $n . "_" . convertAnoIDtoLabel($this->fkAno) . "_Brasil.csv");
             } else {
                 $n2 = $this->getEstadoNome();
                 $n2 = str_replace(" ", "_", $n2);
                 download_send_headers("AtlasIDHM_RankingMunicipal_" . $n . "_" . convertAnoIDtoLabel($this->fkAno) . "_{$n2}.csv");
             }
         } else {
             if ($espc == "estadual") {
                 download_send_headers("AtlasIDHM_RankingEstadual_" . convertAnoIDtoLabel($this->fkAno) . ".csv");
             } else {
                 if ($espc == 'rm') {
                     download_send_headers("AtlasIDHM_RankingRM_" . convertAnoIDtoLabel($this->fkAno) . ".csv");
                 } else {
                     if ($espc == 'udh') {
                         download_send_headers("AtlasIDHM_RankingUDH_" . convertAnoIDtoLabel($this->fkAno) . ".csv");
                     }
                 }
             }
         }
         foreach ($this->data as $key => $val) {
             $c = 0;
             echo "sep=;\n";
             echo utf8_decode($lang->getString("cols_ranking_pos") . ";" . $lang->getString("cols_ranking_na") . ";");
             foreach ($val["vs"] as $k => $v) {
                 $or = "desc";
                 $class = "";
                 $class_ds = "";
                 switch ($v["k"]) {
                     case INDICADOR_IDH:
                         echo "{$this->lang->getString("rankin_idhm")} (" . convertAnoIDtoLabel($this->fkAno) . ")";
                         break;
                     case INDICADOR_RENDA:
                         echo "{$this->lang->getString("rankin_renda")} (" . convertAnoIDtoLabel($this->fkAno) . ")";
                         break;
                     case INDICADOR_LONGEVIDADE:
                         echo "{$this->lang->getString("rankin_Long")} (" . convertAnoIDtoLabel($this->fkAno) . ")";
                         break;
                     case INDICADOR_EDUCACAO:
                         echo utf8_decode("{$this->lang->getString("rankin_edu")}") . " (" . convertAnoIDtoLabel($this->fkAno) . ")";
                         break;
                     default:
                         break;
                 }
                 if ($c <= 2) {
                     echo ";";
                 }
                 $c++;
             }
             break;
         }
         echo "\n";
         $ts = false;
         $counter = 0;
         $last = "0";
         $answer = "";
         $j = 0;
         foreach ($this->data as $key => $val) {
             $n = (double) cutNumber($val["vs"][INDICADOR_IDH]['v'], 3, '.');
             if (cutNumber($val["vs"][$this->pOrdem_id]['v'], 3, '.', '') != $last) {
                 $counter++;
             }
             $answer .= "{$val["ot"]} º;";
             $answer .= "{$val["n"]};";
             /*$answer.= str_replace(",", "-", $val["n"]). ",";*/
             $c = 0;
             foreach ($val["vs"] as $k => $v) {
                 $val["vs"][$k]["v"] = cutNumber($v["v"], 3, ',', '');
                 if ($c <= 2) {
                     $answer .= $val["vs"][$k]["v"] . ";";
                 } else {
                     $answer .= $val["vs"][$k]["v"];
                 }
                 $c++;
             }
             $last = $val["vs"][$this->pOrdem_id]['v'];
             $answer .= "\n";
             $ts = !$ts;
             $j++;
         }
         echo utf8_decode($answer);
         if (isset($_POST["cross_data_download"])) {
             $_POST["cross_data_download"] = false;
         }
         die;
     }
 }