简体   繁体   中英

Use Variables inside Array Map Function PHP

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM