dongtuo0828 2017-04-06 20:02
浏览 47
已采纳

如何在PHP中的闭包之外填充数组?

I wrote this

 $result = array();

        array_map(function($row) use ($result) {
            $result[$row->id] = array();
            $result[$row->id]['geojson'] = $row->geojson;
        }, $regions);

and $result is empty at the end.

Is it possible to populate array this way?

  • 写回答

1条回答 默认 最新

  • dsjswclzh40259075 2017-04-06 20:21
    关注

    $result inside the function is a copy of the outer array, so changes you make don't affect the original. You need to use a reference: use (&$result)

    array_map(function($row) use (&$result) {
        $result[$row->id] = array();
        $result[$row->id]['geojson'] = $row->geojson;
    }, $regions);
    

    Or you could simply use foreach

    foreach ($regions as $row) {
        $result[$row->id] = array();
        $result[$row->id]['geojson'] = $row->geojson;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于c++外部库文件宏的问题,求解
  • ¥15 office打开卡退(新电脑重装office系统后)
  • ¥300 FLUENT 火箭发动机燃烧EDC仿真
  • ¥15 【Hadoop 问题】Hadoop编译所遇问题hadoop-common: make failed with error code 2
  • ¥15 vb6.0+webbrowser无法加载某个网页求解
  • ¥15 RPA财务机器人采购付款流程
  • ¥15 计算机图形多边形及三次样条曲线绘制
  • ¥15 根据protues画的图用keil写程序
  • ¥200 如何使用postGis实现最短领规划?
  • ¥15 pyinstaller打包错误