[英]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內部工作的特殊性,如果對數組的單個元素進行引用,然后復制該數組(無論是通過賦值還是在函數調用中按值傳遞),則該引用將作為數組的一部分進行復制。陣列。 這意味着,即使數組具有不同的范圍(例如,一個是函數內的參數而另一個是全局的),對兩個數組中任何一個這樣的元素所做的更改也將在另一個數組(和其他引用)中重復! 在復制時沒有引用的元素以及在數組復制后分配給那些其他元素的引用將正常運行(即獨立於其他數組)。
這將不會很快得到解決。 這是實施中的一個深層問題,解決它會導致速度問題和許多其他問題。這也是可以編碼的東西,因此不會引起大問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.