Maison >développement back-end >tutoriel php >PHP函数array_merge()合并数组的具体方法解析_PHP教程
我们也许对如果原有数组本身已经被重新排序过,那么在数组合并完成以后,你必须针对产生出来的新数组重新再排序一次。下面这个范例就介绍PHP函数array_merge()的使用方式:
<ol class="dp-xml"> <li class="alt"><span><span><? /* 首先建立第一个数组 */ </span></span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">fruitArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array</font></span><span>("apple", "orange", "banana", "Peach", "pear"); </span> </li> <li class=""><span> </span></li> <li class="alt"><span>/* 接下来建立第二个数组 */ </span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">vegArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array</font></span><span>("carrot", "green beans", "asparagus", "artichoke", "corn"); </span> </li> <li class=""><span> </span></li> <li class="alt"><span>/* 现在使用array_merge()函数将两个数组合并成一个新的数组 */ </span></li> <li class=""><span> </span></li> <li class="alt"> <span>$</span><span class="attribute"><font color="#ff0000">goodfoodArray</font></span><span> = </span><span class="attribute-value"><font color="#0000ff">array_merge</font></span><span>($fruitArray, $vegArray); </span> </li> <li class=""><span> </span></li> <li class="alt"><span>/* 最后我们把合并后的新数组的所有元素的键(key)与值(value)都显示在网页上 */ </span></li> <li class=""><span> </span></li> <li class="alt"><span>while (list($key,$value) = each($goodfoodArray)) { </span></li> <li class=""><span> </span></li> <li class="alt"><span>echo "$key : $value<br>"; </span></li> <li class=""><span> </span></li> <li class="alt"><span>} </span></li> <li class=""><span> </span></li> <li class="alt"><span>?> </span></li> </ol>
显示结果如下:
0 : apple
1 : orange
2 : banana
3 : Peach
4 : pear
5 : carrot
6 : green beans
7 : asparagus
8 : artichoke
9 : corn
PHP函数array_merge()在数组合并中的使用方法如上所示。