doufu7835 2013-09-20 12:53
浏览 46
已采纳

还有另一种方式,而不是通过引用来做我想做的事情

I have the following data structure:

A Contract has an array projects, which can have X number of projects. Each Project has an array, subProjects, which contain the same Project type, so theoretically you could have an infinite tree of Project-SubProjects-Project...

Anyway, each project has a unique ID, and I need to search for a given project AND make a modification to that project, starting at the top level, and then store the changed contract back to my session. Currently, I'm doing it via a recursive function that returns a reference to the project it finds, but the more I'm searching, the more it seems people don't like PHP references. I'm not sure why, could someone explain the problems? Is there a better way to do what I want?

Some code:

// Get the associative array version of the contract (it's stored as JSON)
$contract = json_decode($contract, true);

if(array_key_exists('projects', $contract))
{
    $resultProject = &$this->findProject($contract['projects'], $projectId);

    if($resultProject)
    {
        $resultProject[$inputData['propertyName']] = $inputData['value'];

         \Session::put('workingContract', json_encode($contract));

        // return 200
    }
}

// Return 404

/**
 * Performs a depth-first search to find a project.
 *
 * @param array $projects
 * @param $projectId
 * @return null
 */
private function &findProject(array &$projects, $projectId)
{
    foreach($projects as &$project)
    {
        if($project['_id']['$id'] == $projectId)
        {
            return $project;
        }

        if(array_key_exists('subProjects', $project))
        {
            $result = &$this->findProject($project['subProjects'], $projectId);
            return $result;
        }
    }

    $null = null; // TODO: shitty hack for inability to return null when function returns a reference. Need to rethink use of references in general. Is there another way???
    return $null;
}
  • 写回答

1条回答 默认 最新

  • drus40229 2013-09-20 13:19
    关注

    Why not just create an array with all your projects (a flat array), indexed by ID. Let each Project object have an ->id property that you can refer to. Problem solved?

    Also, if the Project doesn't exist in the flat array, I see absolutely no problem in returning null.

    class Contract {
       private $projects_flat = array();
    
       ....
    
       private function get_project($id) {
          return (isset($this->projects_flat[$id]) ? $this->projects_flat[$id] : null)
       }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?