dougou2937 2017-11-29 23:04
浏览 73
已采纳

在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?

  • 写回答

1条回答 默认 最新

  • duanduji2986 2017-11-29 23:08
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 vue2登录调用后端接口如何实现