How could I reduce the number of loops in my code. Current code is a dummy example but as I am scraping content from a URL and it contains around 6K-7K li traversal to scrap data so speed is a concern in my app.
1) I am scraping data from a URL using Simple PHP DOM parser, so my first concern is whether it is a relevant way to traverse DOM for scraping data(around 6K-7K li elements) or file_get_contents()
will be an appropriate.
2) How do i reduce the number of loops in the below mentioned code, I tried but fails-
My whole code
<?php
$arrunsort = array('ab','ad','ar','cd','cb','sc','si','wa','za');
$prevLabel = array();
$currLabelarr = array();
$newarr = array();
foreach( $arrunsort as $sortelem )
{
$currLabel = substr($sortelem, 0, 1);
if( $currLabel !== $prevLabel )
{
//echo '<h2>',strtoupper($currLabel),'</h2>','<br>';
$currLabelarr[] = $currLabel;
$prevLabel = $currLabel;
}
}
foreach($currLabelarr as $arrkeymatch)
{
$newarr[$arrkeymatch] = array();
$i = 0;
foreach($arrunsort as $value)
{
if( $arrkeymatch == (substr($value, 0, 1)) )
{
//echo '<li>',$value,'</li>';
$newarr[$arrkeymatch][$i] = $value;
$i++;
}
}
}
foreach($newarr as $key=> $val)
{
echo "<h3>",$key,'</h3>';
echo '<ul>';
foreach($val as $myval)
{
echo '<li>',$myval, '</li>';
}
echo '</ul>';
}
Now my tries to reduce the number of loops-
- Comment the last
foreach
loop - Uncomment
echo '<h2>',strtoupper($currLabel),'</h2>','<br>';
&echo '<li>',$value,'</li>';
But the li items are coming below, let me know how could I solve this to minimize loops.
EDIT
In the meantime I checked Caching but as a noob I am not very sure if it a genuine method of caching in my case.