[英]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_1 =选项一的所有可能选项的列表
Array_2 = list of all the possible options for option two when option one == Array_1[0] Array_2 =选项一== 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_1 = ['大杯子','小杯子']
Array_2 = [ 'one color print', 'two color print', 'three color print' ] Array_2 = ['一种彩色打印','两种彩色打印','三种彩色打印']
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. 但是,尽管在第二个数组映射之外正确,但$ option_one_arr在第二个数组映射内部始终= NULL。
Thoughts? 思考?
All functions in PHP have a limited scope. PHP中的所有功能都具有有限的范围。 You cannot access $option_one_arr within a function unless you import that variable into the function. 除非您将变量导入到函数中,否则不能访问函数中的$ option_one_arr。
With anonymous functions, or closures, you can import variables with use
. 使用匿名函数或闭包,可以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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.