PHP数组的引用与值复制?
发布时间:2020-12-13 17:04:29 所属栏目:PHP教程 来源:网络整理
导读:我错过了一些明显的东西.这是一个简单的 PHP,散落着调试回声: function echo_rows($res) { $rows= array(); while ($row= $res-fetch()) { echo $row['ccorID'] . "rn"; $rows[]= $row; echo $rows[0]['ccorID'] . "rn"; } echo "---.---rn"; echo co
我错过了一些明显的东西.这是一个简单的
PHP,散落着调试回声:
function echo_rows(&$res) { $rows= array(); while ($row= $res->fetch()) { echo $row['ccorID'] . "rn"; $rows[]= $row; echo $rows[0]['ccorID'] . "rn"; } echo "---.---rn"; echo count($rows) . "rn"; foreach($rows as $row) { echo $row['ccorID'] . "rn"; } echo json_encode($rows); } 这是我在回复中看到的内容: 0 0 3 3 13 13 182 182 ---.--- 4 182 182 182 182 我觉得很清楚: – >我有4行数据 任何人都知道我需要做什么来获得$row的副本(这是一个关联数组)? 谢谢. 编辑:因为很多人都坚持要知道$res是什么,所以这是课程.我真的相信这更容易混淆而不是启发(因此我的OP遗漏). class mysqlie_results { private $stmt; private $paramArray= array(); private $assocArray= array(); public function __construct(&$stmt) { $this->stmt= $stmt; $meta= $stmt->result_metadata(); while ($colData= $meta->fetch_field()) { $this->paramArray[]= &$this->assocArray[$colData->name]; } call_user_func_array(array($stmt,'bind_result'),$this->paramArray); $meta->close(); } public function __destruct() { $this->stmt->free_result(); } public function fetch() { return $this->stmt->fetch()? $this->assocArray : false; } } 解决方法
我们来仔细看看
while ($colData= $meta->fetch_field()) { $this->paramArray[]= &$this->assocArray[$colData->name]; } call_user_func_array(array($stmt,$this->paramArray); 在那里你有你的参考,这是造成麻烦的.如果复制包含引用的数组,则结果仍然是包含引用的数组. 尝试 while ($row= $res->fetch()) { var_dump($row); 你会看到$row也包含引用. paramArray,assocArray和$row中的所有相应元素实际引用相同的值.因此当你调用return $this-> stmt-> fetch()时,它不仅影响paramArray而且影响所有这些引用,一直到$rows,因为$rows [] = $row;仍然只复制数组但不“取消引用”元素. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |