繁体   English   中英

数组值意外更改

[英]Array values changing unexpectedly

我正在使用cakephp 1.2,并且我有一个数组,该数组似乎具有值更改,即使未对该变量进行操作也是如此。 下面是导致我麻烦的代码。

请注意-更新更改变量名称对结果没有影响。

function findCountByString($string, $myArr=array()) {

$main_conditions['or'] = array();
$main_conditions['or']['Article.title LIKE '] = '%'.$string.'%';
$main_conditions['or']['Article.html_content LIKE '] = '%'.$string.'%';
$conditions['and'][] = $main_conditions;
$filter_conditions['or'] = array();
if(count($myArr) > 0) {
    # UPDATE NUMBER 2
    # if I comment out the below line everything is fine, this makes no sense!!!
    $filter_conditions['or']['ArticleEntity.entity_id'] = $myArr;
    $conditions['and'][] = $filter_conditions;
}

echo "Start of findCountByString()";
var_dump($myArr);

$test  = $this->find('count', array(
    'conditions' => $conditions,
    'joins' => array('LEFT JOIN `articles_entities` AS ArticleEntity ON `ArticleEntity`.`article_id` = `Article`.`id`'),
    'group' => 'Article.id'
    ));

echo "End of findCountByString()";
var_dump($myArr);

return $test;

}

我得到以下输出:

Start of findCountByString()

array(4) {
  [0]=>
  string(36) "4bdb1d96-c680-4c2c-aae7-104c39d70629"
  [1]=>
  string(36) "4bdb1d6a-9e38-479d-9ad4-105c39d70629"
  [2]=>
  string(36) "4bdb1b55-35f0-4d22-ab38-104e39d70629"
  [3]=>
  &string(36) "4bdb25f4-34d4-46ea-bcb6-104f39d70629"
}

End of findCountByString()

array(4) {
  [0]=>
  string(36) "4bdb1d96-c680-4c2c-aae7-104c39d70629"
  [1]=>
  string(36) "4bdb1d6a-9e38-479d-9ad4-105c39d70629"
  [2]=>
  string(36) "4bdb1b55-35f0-4d22-ab38-104e39d70629"
  [3]=>
  &string(38) "'4bdb25f4-34d4-46ea-bcb6-104f39d70629'"
}

我数组中的值已更改,我不知道为什么?

有什么建议么?

$filters可能是一个引用,它在方法调用中被更改,或者pr本身具有状态/副作用。 通过删除对pr的调用并将其替换为var_dump可以消除第二个选项。

您的代码段未提供足够的信息。 最好的选择是调试器。

编辑:您的最后一个元素是一个引用(可能是通过引用的foreach的残余)。 修复构建数组的代码,以使它不会在最后一个元素中留下引用。

似乎是通过引用访问PHP数组的错误

由于PHP内部工作的特殊性,如果对数组的单个元素进行引用,然后复制该数组(无论是通过赋值还是在函数调用中按值传递),则该引用将作为数组的一部分进行复制。阵列。 这意味着,即使数组具有不同的范围(例如,一个是函数内的参数而另一个是全局的),对两个数组中任何一个这样的元素所做的更改也将在另一个数组(和其他引用)中重复! 在复制时没有引用的元素以及在数组复制后分配给那些其他元素的引用将正常运行(即独立于其他数组)。

这将不会很快得到解决。 这是实施中的一个深层问题,解决它会导致速度问题和许多其他问题。这也是可以编码的东西,因此不会引起大问题。

http://bugs.php.net/bug.php?id=8130

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM