Support

Account

Home Forums General Issues Get one of each select value if it's used

Helping

Get one of each select value if it's used

  • So I have a post with a repeater, inside of that repeater every row has a select with 8 options, let’s call it “size”.

    The repeater can consist of a lot of products with different sizes. And on the post page I’m listing all the repeater rows in a table.

    On top of the table I’m building a filter function where you should be able to select “show all” based on if it’s available or just show the specific sizes.
    The show all is based on another select and I’ve solved it the following code:

    <?php
      $available = false;
      $value = 'available';
      if (have_rows('item')) {
        while(have_rows('item')) {
          the_row();
          if ($value == get_sub_field('status')) {
            $available = true;
          }
        }
      }
    ?>

    And then I output the filter button using:

    <?php if ($available) { ?>
              	<li class="filter-btn"><a href="">Show all</a></li>
              <?php } ?>

    So my goal is to create a function where I go through the select for sizes for every row and create filter buttons for the sizes available.
    I have a solution that works but is really bad and not scalable and just terrible, it works like the above code but it’s a check for EVERY different size and then just an if statement to show the correct filter button or not. It doesn’t seem that smart.

    I would like to check the repeater for all values that exist, and then output one filter button for each size if that value exists in the repeater. What would be the smartest and easiest way to solve that?

    Thanks

  • I would loop over the repeater once, gather all of the values into an array and then use the array.

    A simple example:

    
    $values = array();
    while (have_rows($repeater) }
      the_row();
      $value = get_field('sub_field');
      if (!in_array($value, $values) {
        $values[] = $value;
      }
    }
    // loop over the array and do something with each value.
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.