2

My task is to get two create two arrays:

Array_1 = list of all the possible options for option one

Array_2 = list of all the possible options for option two when option one == Array_1[0]

Given these rows...

    $rows = [
        (object) ['option_one' => 'large mug', 'option_two' => 'one color print'],
        (object) ['option_one' => 'large mug', 'option_two' => 'two color print' ],
        (object) ['option_one' => 'large mug', 'option_two' => 'three color print' ],
        (object) ['option_one' => 'small mug', 'option_two' => 'one color print' ],
        (object) ['option_one' => 'small mug', 'option_two' => 'two color print' ],
    ];

Then my output would be

Array_1 = [ 'large mug', 'small mug']

Array_2 = [ 'one color print', 'two color print', 'three color print' ]

I have tried to accomplish this using array maps as follows...

    $option_one_arr = array_unique ( array_map(function($row) { return $row->option_one; }, $rows) );
    $option_two_arr = array_unique ( array_map(function($row) {
        // ($option_one_arr == NULL) == TRUE
        if ($row->option_one === $option_one_arr[0]) 
            return $row->option_two;
    }, $rows) );
    $to_render = [$option_one_arr, $option_two_arr];

    echo '<pre>';
    var_dump($to_render);

However, $option_one_arr always = NULL inside the second array map despite being correct outside the second array map.

Thoughts?

1 Answer 1

8

All functions in PHP have a limited scope. You cannot access $option_one_arr within a function unless you import that variable into the function.

With anonymous functions, or closures, you can import variables with use.

array_map(function($row) use ($option_one_arr) {
    // ($option_one_arr == NULL) == TRUE
    if ($row->option_one === $option_one_arr[0]) 
        return $row->option_two;
}, $rows);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.