recursivité sur un tableau
Posté : 22 nov. 2016, 18:51
par flo_dev_92
Je cherche à partir d'un tableau regroupant des années, à obtenir une string qui, si les années se suivent séparent les dites années par un tiret, sinon par une simple virgule.
Pour le tableau suivant le résultat attendu serait
$str = 2000,2002,2004-2005
$podYears = array(2000,2002,2004,2005);
$length = count($podYears);
$strYears ="";
$indice = 0;
function getStrYears($t_year,$length,$indice,$strYears)
{
if ($indice >= $length-1)
return $strYears.= $t_year[$indice];
else
{
if($t_year[$indice]+1 == $t_year[$indice+1])
$strYears.= $t_year[$indice]."-";
else
$strYears.= $t_year[$indice].",";
getStrYears($t_year,$length,$indice+1,$strYears);
}
}
$res = getStrYears($podYears,$length,$indice,$strYears);
echo $res;
Re: recursivité sur un tableau
Posté : 22 nov. 2016, 19:38
par Naroth
Bonjour,
La récursivité est-elle une obligation ?
Si ce n'est pas un obligation, il vaut mieux parcourir bêtement le tableau
$podYears = array(2000,2002,2004,2005,2018,2019,3000,3001);
$res = "";
//pour tous les élements sauf le dernier
for($i = 0; $i < count($podYears)-1; $i++)
{
//Si la valeur de l'element courant +1 est égale à la valeur du prochaine element
if($podYears[$i]+1 === $podYears[$i+1])
{
//On ajoute l'année et le tiret à la string
$res .= $podYears[$i]."-";
}
//Sinon donc val element courant +1 != val prochaine element
else
{
//On ajoute l'année et la virgule à la string
$res .= $podYears[$i].",";
}
}
//On ajoute le derniere element
$res .= $podYears[count($podYears)-1];
//On affiche
echo $res;
//resultat : 2000,2002,2004-2005,2018-2019,3000-3001
Re: recursivité sur un tableau
Posté : 23 nov. 2016, 17:22
par flo_dev_92
Merci Naroth pour cette réponse. Effectivement, pas besoin de récursivité.
Je m'en suis tirée tout de même comme ceci : (la seconde fonction c'est juste pour obtenir une séquence si j'ai plusieurs années qui se suivent)
$podYears = array(1995,2000,2001,2002,2004,2006,2007);
$length = count($podYears);
$strYears ="";
$indice = 0;
function getStrYears($t_year,$length,$indice,$strYears)
{
if ($indice >= $length-1)
{
$strYears.= $t_year[$indice];
return $strYears;
}
else
{
if($t_year[$indice]+1 == $t_year[$indice+1])
{
$strYears.= $t_year[$indice]."-";
}
else
$strYears.= $t_year[$indice].",";
return getStrYears($t_year,$length,$indice+1,$strYears);
}
}
$res = getStrYears($podYears,$length,$indice,$strYears);
echo splitYears($res ,",","-");
function splitYears($str,$separator1,$separator2)
{
$newTabYears = array();
$newStr = "";
$tabTemp1 = explode($separator1,$str);
//echo "<pre>".print_r($tabTemp1,true)."</pre>";
for($i=0;$i<count($tabTemp1);$i++)
{
if(strpos($tabTemp1[$i],$separator2)>0)
{
$anneeDbt = substr($tabTemp1[$i],0,4);
$anneeFin = substr($tabTemp1[$i],-4);
$int = $anneeDbt ."-".$anneeFin;
$newTabYears[] = $int;
}
else
{
$newTabYears[] = $tabTemp1[$i];
}
}
$newStr = implode(",",$newTabYears);
return $newStr;
}