Jump to content

Check for value existence in a repeater (within a repeater) without a loop?


a-ok
 Share

Recommended Posts

I have a JSON multi-dimensional array of products from Shopify that I am looping through. Each product has 3 options and each option can have infinite numbers of values.

For example:

  • Lamp (product)
    • Glass Finish (option)
      • Clear (value)
      • Smoke (value)
    • Metal Finish (option)
      • Polished Chrome (value)
    • Drop (option)
      • 600mm (value)
      • 800mm (value)

Within the loop I am creating rows within a repeater field (one for each option and then a repeater within each option for each value).

This is all fine BUT I want to do a few checks as the array of products is cached to every 30 minutes so if the cache was updated and either an option was removed or a value to that option was added then it should update.

I have my first check in place (loop through all the existing repeater options that have been added, before doing anything, and if an option already exists then skip it (and thus not creating multiple of the same options).

What I need to do is to check each of the values to see if any new ones have been added. I can write the code to actually add the value to the repeater field but I am unsure how to check as by this point, if the option already exists, it skips over.

foreach($product['options'] as $option) {

    foreach($p->shop_product_options as $options) {

         // If this option already exists... then skip the parent loop on this product
        if ($options->global_text == $option['name']) {
            continue 2;
        }

    }

    $options = $p->shop_product_options->getNew();
    $options->of(false);
    $options->global_text = $option['name'];
    $options->save();
    $p->shop_product_options->add($options);
    foreach($option['values'] as $o) {
        $values = $options->shop_product_options_option->getNew();
        $values->of(false);
        $values->global_text = $o;
        $values->save();
        $options->save();
        $options->shop_product_options_option->add($values);
    }
    $options->save();
}
Link to comment
Share on other sites

Hi,

without a loop, you could use selector subfields to find your options like the following:

$page->repeater->find("sub_repeater.field=value");

 

So for you code :

$option_name = $p->shop_product_options->find("shop_product_options_option.global_text={$option['name']}");

if(is_null($option_name) || !count($option_name)) {
    continue;
}
else {
    // do stuff
}

 

  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...