Xhynk
Xhynk

Reputation: 13840

while loop optimization a little bit

I've got a while loop running that grabs all the posts on my site

while ( $all_query->have_posts() ) : $all_query->the_post();

there is meta data in each on that I need to play with. It's a field called 'rate' and I need to merge like values, 1-5.

Currently, I've got this

while ( $all_query->have_posts() ) : $all_query->the_post();
    $fives = 0;
    $fours = 0;
    $threes = 0;
    $twos = 0;
    $ones = 0;
    if(get_post_meta($post->ID, 'rate', true) == 'five') { 
        $fives = $fives + 5;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'four') { 
        $fours = $fours + 4;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'three') { 
        $threes = $threes + 3;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'two') { 
        $twos = $twos + 2;
    }
    if(get_post_meta($post->ID, 'rate', true) == 'one') { 
        $ones = $ones + 1;
    }
    endwhile;

it works, but it's really gross.

Is there a more optimized and clean way to do something like this?

Upvotes: 1

Views: 193

Answers (1)

Jon
Jon

Reputation: 437336

A little bit of array manipulation can greatly simplify this:

$counts = array_fill(1, 5, 0);
$labels = array(1 => 'one', 'two', 'three', 'four', 'five');

while(...) {
    $index = array_search(get_post_meta($post->ID, 'rate', true), $labels);
    $counts[$index] += $index;
}

The totals are kept inside $counts, with $counts[1] being the total of ones. $labels is there to help match the textual representation with the array positions inside $counts -- this could of course be done with a plain switch instead.

The loop uses array_search to convert textual representations to array indexes, then simply increments the corresponding count by an amount equal to the index.

Production code should of course also account for the possibility of array_search returning false.

Upvotes: 4

Related Questions