【问题标题】:CakePHP 1.2.6 / PHP5.2.12 Error in Array Loop in Assignment by ReferenceCakePHP 1.2.6 / PHP5.2.12 引用赋值中的数组循环错误
【发布时间】:2010-02-25 18:37:11
【问题描述】:

我正在检索一堆数据,但由于某种原因,其中一些数据已损坏。例如,我有一些 Post 模型,每个模型都与 Comment 模型(hasMany)相关,并且每个 Comment 模型都属于一个用户。检索数据时,这是我从数据库中获取的 cmets 数据:

[Post] => Array
(
)

[Comments] => Array
(
    [0] => Array
        (
            [content] => "2010 has definitely been a busy year!"
            [created] => 2010-02-10 13:47:15
            [user_id] => 18
            [post_id] => 1
            [User] => Array
                (
                    [id] => U8
                    [username] => Uace
                    [first_name] => Uace
                )

            [_explicitType] => Comment
        )

    [0] => Array
        (
            [content] => "I can't wait..."
            [created] => 2009-12-10 13:57:36
            [user_id] => 18
            [post_id] => 1
            [User] => Array
                (
                    [id] => U8
                    [username] => Uace
                    [first_name] => Uace
                )

            [_explicitType] => Comment
        )

)

每个 Comments[i][User] 数组的第一个字符已替换为大写 U,但在每种情况下它应该不同(例如 ID 为 18,用户名 Jace 等)。

我将其追溯到我正在使用的数组操作,用于在 afterFind() 函数中为 Flex 交互分配一个 _explicitType 字段(谢谢,Paweł Mysior!)。这是我陷入 _explicitType 的循环:

if (is_array($results)) {
    foreach ( $results as &$item )
    {
            $item['_explicitType'] = $this->name;

    }
} else {
    $item[$this->name]['_explicitType'] = $this->name;
}

我认为它与引用分配有关,但我想不出它为什么会发生。

【问题讨论】:

  • FOR 循环似乎可以在不破坏数组的情况下工作,但是在尝试处理没有数字索引的数组时会变得混乱。

标签: php arrays pass-by-reference cakephp-1.2


【解决方案1】:

这很奇怪。

在 core.php 中将 debug 设置为 2,然后查看页面底部的 sql 日志,也许你会在那里找到一些东西。还要查看所有模型(应用程序、帖子、用户、评论)。可能有一些 beforeFind() 导致这种情况发生。当您执行简单的 User->find() 时也会发生这种情况吗?

顺便说一句。您如何在这里检索数据?

【讨论】:

  • 啊,我想我找到了。我正在用 afterFind() 做一些事情。请参阅上面的修改后的帖子。
【解决方案2】:

我认为找到了问题所在。我在 foreach() 中移动了对数组的检查,现在它似乎工作正常。我认为这是因为在非数组项目上,它实际上破坏了一些东西。这是我在测试用例上记录的更改循环:

foreach ( $results as &$item )
{
    if(is_array($item)) {
        $item['_explicitType'] = $this->name;
    } else {
        $copy = $item;
        $copy['_explicitType'] = $this->name;
        $this->log($copy, LOG_DEBUG);
    }
}

果然,它记录了用大写 U 代替第一个字母的数据。

【讨论】:

    猜你喜欢
    • 2018-02-02
    • 2016-01-17
    • 2019-06-27
    • 1970-01-01
    • 2017-03-21
    • 2017-08-04
    • 2012-11-19
    • 2021-07-27
    • 2011-05-06
    相关资源
    最近更新 更多