par
flo_dev_92 » 23 nov. 2016, 17:22
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;
}
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;
}