php - Iterating through foreach loop - group sorting effiiceny -
i have loop running in project not happy , wondered if there more efficient way of achieving this?
i have array so
$myarray = ["value1", "value2", "value3"];
then want go through object ($sponsors) , print out values on has field matches value in $myarray[]. so:
<?php foreach ($myarray $value): ?> <?php foreach ($sponsors $post) : setup_postdata( $post );?> <?php if($post['somevalue'] == $value): ?> //do work <?php endif; ?> <?php endforeach; ?> <?php endforeach; ?>
this working fine, might mean 50-60 loops grab , print out few bits of markup. there better way this?
edit note: (based on initial replies) order of $myarray important, allows me group 'value1' , 'value2' etc
you can rid of outer foreach loop
<?php foreach ($sponsors $post) : setup_postdata( $post );?> <?php if(in_array($post['somevalue'], $myarray)): ?> //do work <?php endif; ?> <?php endforeach; ?>
update
given $sponsers
array of posts
, can improve peformance filterig posts based on value native array_filter()
function there less posts foreach
iterate over.
after there no need if
statement improve performance.
<?php foreach ($myarray $value): ?> <?php $filteredposts = array_filter($sponsors, function($post) use ($value) { return $post['somevalue'] == $value; }); ?> <?php foreach ($filteredposts $post) : setup_postdata( $post );?> // <?php endforeach; ?> <?php endforeach; ?>
Comments
Post a Comment