开发者

Why a loop over MySQL query change an array which has nothing to do with the query?

I have the following piece of code:

print_r($queries);
$id2query = array(); 
while ($res_array = mysql_fetch_array($results)) {
    $id = $res_array['id'];
    $query = $res_array['query'];
    $id2query[$id] = $query;
}
print_r($queries);

The interesting thing is that printr_r before and after the loop return different things.

Does anybody know how it can be possible?

ADDED

$queries is an array. It shown code is a part of a function and $queries is one of the arguments of the function. Before the loop it开发者_如何学C returns:

Array ( [0] => )

and after the loop it returns:

Array ( [0] => web 2.0 )

ADDED 2

web 2.0 comes from $res_array. Here is the content of the $res_array:

Array ( [0] => 17 [id] => 17 [1] => web 2.0 [query] => web 2.0 [2] 

But I do not understand how a value from $res_array migrates to $queries.

ADDED 3

I tried

print "AAAA".var_dump($queries)."BBB";

it returns AAABBB.

ADDED 4

I have managed to use var_dump in the correct way and this is what it returns before the loop:

array(1) { [0]=> &string(0) "" }

This is what I have after the loop:

array(1) { [0]=> &string(7) "web 2.0" }

But I do not understand what it means.


The var_dump below ADDED 4 shows it, the array contains a reference to a string. So it is not a copy of that string, it is something like a pointer (I know, they are not real pointers, see PHPDocs below) to the original string. So if that one gets changed, the references shows the changed value too.

I'd suggest you have a look at:
PHPDoc References
PHPDoc What references do

Example code:

$s = "lulu";
$a = array(&$s);
var_dump($a);
$s = "lala";
var_dump($a);

First var_dump will return:

array(1) {
 [0]=>
 &string(4) "lulu"
}

And the second:

array(1) {
 [0]=>
 &string(4) "lala"
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜