Skip to content

Instantly share code, notes, and snippets.

@ctf0
Last active May 14, 2020 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctf0/aca06ea1bdf98add9e785b2aef7cea01 to your computer and use it in GitHub Desktop.
Save ctf0/aca06ea1bdf98add9e785b2aef7cea01 to your computer and use it in GitHub Desktop.
<?php

protected function groupSimilarByFunc($array, $fieldName, $similarity, $ignore_pattern = null)
{
    $crntLocale  = LaravelLocalization::getCurrentLocale();
    $list        = [];

    foreach ($array as $one) {
        $field = $one->$fieldName();

        // extra for multi locale (other than 'en')
        //if ($crntLocale !== LaravelLocalization::getDefaultLocale()) {
        //    if (str_contains($field, "$crntLocale/")) {
        //        $field = str_replace("$crntLocale/", '', $field);
        //    }
        //
        //    $field = str_replace($crntLocale, '', $field);
        //}

        // loop
        if (str_contains($field, $similarity)) {
            $found = strstr($field, $similarity, true);

            if (preg_match('/^' . $found . '/', $field)) {
                $list[$found][] = $one;
            } else {
                $list[$field][] = $one;
            }
        } else {
            $list[$field][] = $one;
        }
    }

    if ($ignore_pattern) {
        $keys = preg_grep($ignore_pattern, array_keys($list));

        foreach ($keys as $key) {
            unset($list[$key]);
        }
    }

    return $list;
}

protected function groupSimilarByObj($array, $fieldName)
{
    $total = [];

    foreach ($array as $key) {
        if (in_array($key->{$fieldName}, $total)) {
            $total[$key->{$fieldName}][] = $key;
        } else {
            $total[$key->{$fieldName}][] = $key;
        }
    }

    return $total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment