Recode algorithm for merged cells on HTML table
Some tips to make it faster 


Use references in foreach loops with &amp;, like foreach ($matrix as $pkey =&gt; &amp;$pvalue)
Don't use $htmlx variable, just output everything with echo
For some scecific purposes you may use ob_start(), ob_get_contents() and ob_end_clean() - it's much faster than concat like $html_d.=
Don't output html with php, just close php tags 

if($d==1){ ?&gt;
   &lt;td&gt;&lt;?php echo $dkey ?&gt;&lt;/td&gt;&lt;td&gt;&lt;?php echo $dvalue ?&gt;&lt;/td&gt;
&lt;?php }else{ ?&gt;