Jack Robson Jack Robson - 1 year ago 110
PHP Question

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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download