Heim  >  Artikel  >  Backend-Entwicklung  >  PHP为什么使用array_combine方法影响了原数组

PHP为什么使用array_combine方法影响了原数组

WBOY
WBOYOriginal
2016-08-04 09:19:291378Durchsuche

请看下面的代码:

在处理之前有两个数组arrTitlearrHref,

其中arrTitle内容如下:

PHP为什么使用array_combine方法影响了原数组

arrHref内容如下:

PHP为什么使用array_combine方法影响了原数组

<code class="php">//将title数组中首元素取出,作为栏目标题
foreach ($arrTitle as &$title) {
    $text [] = $title[0];
    unset($title[0]);
}

//将href数组中首元素取出,作为栏目url
foreach ($arrHref as &$href) {
    $url [] = $href[0];
    unset($href[0]);
}

print_r($arrTitle);
//重新组织title项
$title = array_combine($text, $url);

print_r($arrTitle);die;</code>

运行上面的PHP代码,把title和href中每项的首元素取出并去除,然而问题来了,在执行array_combine之前,$arrTitle是这样的:

PHP为什么使用array_combine方法影响了原数组

然而在执行array_combine之后,$arrTitle变成了这样:

PHP为什么使用array_combine方法影响了原数组

为什么,$arrTitle的最后一个元素变成了array_combine()的结果,而array_combine()函数并没有对$arrTitle执行了修改?

回复内容:

请看下面的代码:

在处理之前有两个数组arrTitlearrHref,

其中arrTitle内容如下:

PHP为什么使用array_combine方法影响了原数组

arrHref内容如下:

PHP为什么使用array_combine方法影响了原数组

<code class="php">//将title数组中首元素取出,作为栏目标题
foreach ($arrTitle as &$title) {
    $text [] = $title[0];
    unset($title[0]);
}

//将href数组中首元素取出,作为栏目url
foreach ($arrHref as &$href) {
    $url [] = $href[0];
    unset($href[0]);
}

print_r($arrTitle);
//重新组织title项
$title = array_combine($text, $url);

print_r($arrTitle);die;</code>

运行上面的PHP代码,把title和href中每项的首元素取出并去除,然而问题来了,在执行array_combine之前,$arrTitle是这样的:

PHP为什么使用array_combine方法影响了原数组

然而在执行array_combine之后,$arrTitle变成了这样:

PHP为什么使用array_combine方法影响了原数组

为什么,$arrTitle的最后一个元素变成了array_combine()的结果,而array_combine()函数并没有对$arrTitle执行了修改?

<code>**$title** = array_combine($text, $url);
</code>

这里的$title 和上面循环里的 $title 重名,改个名字就好了。php 里没有块作用域。

此bug已经解除,感谢 @whyreal 指出重名问题。

由于在foreach循环中,以引用方式遍历数组,当循环结束时,$title指向了$arrTitle的最后一组元素。

由于PHP没有块级作用域,在$title = array_combine($arr1, $arr2),之后这个$title同时修改了它指向的$arrTitle的最后一组元素,由此产生了bug。

修改后面$title的名称解除此bug。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn