Help with refactoring collection methods / am I reinventing the wheel?

Posted 2 months ago by wturrell

When you use crossJoin(), the matrix of permutations it produces is a simple array. I wanted to add keys to it, to make it easier to debug and reuse with other functions, as per my docblock below.

  • is there a Collection method that'll add keys to an array element for me, which I could just use instead?
  • How could I get rid of that for loop? I want it to return an associative array, rather than a collection?
  • what's the correct type hint for a collection (for the first parameter of AddKeysToMatrix)?

Many thanks, William

    /**
     * Make our matrix(s):
     * (a) easier to understand/debug
     * (b) re-usable when we have different fields (e.g. country vs region)
     *     that we want to pass to a function as a single parameter not
     *     a long series of fields
     *
     * @param $matrix
     * @param $field_order
     * @return array
     */
    public static function addKeysToMatrix($matrix, array $field_order) {

        $output = collect($matrix)->map(function($input) use ($field_order) {

            $pos = 0;
            $new_element = [];

            foreach($input as $value) {
                $new_element[$field_order[$pos]] = $value;
                $pos++;
            }

            return $new_element;
        });

        return $output;
    }

Please sign in or create an account to participate in this conversation.