php - How to loop trought array and create array from common values? [Solved] -
i need filter array , spilt them different arrays. here actual working , slow code:
-----> http://viper-7.com/gvrbvp
but method still slow, think. @ least 3 loops... scan 1 time array , create array on fly, tried this:
$stray = json_decode('[{"id":"1","zona":"pescara"},{"id":"2","zona":"pescara"},{"id":"3","zona":"teramo"},{"id":"4","zona":"pescara"},{"id":"5","zona":"pescara"},{"id":"6","zona":"teramo"},{"id":"7","zona":"pescara"},{"id":"8","zona":"pescara"},{"id":"9","zona":"pescara"},{"id":"10","zona":"pescara"},{"id":"11","zona":"pescara"},{"id":"12","zona":"pescara"},{"id":"13","zona":"teramo"},{"id":"14","zona":"chieti"},{"id":"15","zona":"chieti"},{"id":"16","zona":"aquila"},{"id":"17","zona":"chieti"},{"id":"18","zona":"chieti"},{"id":"19","zona":"chieti"},{"id":"20","zona":"chieti"},{"id":"21","zona":"campobasso"},{"id":"22","zona":"aquila"},{"id":"23","zona":"pescara"},{"id":"24","zona":"pescara"},{"id":"25","zona":"pescara"},{"id":"26","zona":"pescara"},{"id":"27","zona":"chieti"},{"id":"28","zona":"pescara"},{"id":"29","zona":"pescara"},{"id":"30","zona":"chieti"},{"id":"31","zona":"pescara"},{"id":"32","zona":"chieti"},{"id":"33","zona":"teramo"},{"id":"34","zona":"teramo"},{"id":"35","zona":"teramo"},{"id":"37","zona":"teramo"},{"id":"39","zona":"pescara"}]',true); $all_cat = array(); foreach($stray $row) { $item_cat = $row['zona']; if($$cat) { /* check if category array exist */ $cat = array(); /* if not, create array */ if( !in_array($item_cat,$$item_cat) ) { /* , add value */ array_push($$item_cat,$row); } array_push($all_cat, $cat); /* add new category index of categories */ } else { if( !in_array($item_cat,$$item_cat) ) { /* otherwise add value */ array_push($$item_cat,$row); } } } echo '<pre>'.print_r($cat,true).'</pre>';
if understand correctly, simplify
foreach($stray $row) { if(!isset($$row['zona'])) { $$row['zona']=array(); } ${$row['zona']}[] = $row; }
so viper-7 like
$stray = json_decode(...[removed simplify]...,true); foreach($stray $row) { if(!isset($$row['zona'])) { $$row['zona']=array(); } ${$row['zona']}[] = $row; } echo 'pescara :<pre style="max-height: 50px; overflow: auto">'.print_r($pescara,true).'</pre>'; echo 'teramo :<pre style="max-height: 50px; overflow: auto">'.print_r($teramo,true).'</pre>'; echo 'chieti :<pre style="max-height: 50px; overflow: auto">'.print_r($chieti,true).'</pre>'; echo 'aquila :<pre style="max-height: 50px; overflow: auto">'.print_r($aquila,true).'</pre>'; echo 'campobasso :<pre style="max-height: 50px; overflow: auto">'.print_r($campobasso,true).'</pre>';
Comments
Post a Comment