您的位置:首页 > 编程语言 > PHP开发

php 操作数组array_merge使用时数组包含数字键名的问题解决方法

2016-05-01 10:16 886 查看
问题如下:

<!DOCTYPE html>
<html>
<body>

<?php
$age=array("123"=>"35");
$a=array();
$a=array_merge($a,$age);
print_r($a);
?>

</body>
</html>


输出:Array ( [0] => 35 )

其实我想要的结果是Array ( [123] => 35 ) ,我想要合并,怎么办呢?

解决:分为两个索引数组。再最后连接起来。

<?php
function get_all_switch()
{
$myinfo = $_SESSION['member'];
$sql = "select switch_name,token from switch where acount='".$myinfo['acount']."'";
$result =  mysql_query($sql);

$switch_name_temp=array();
$token_temp=array();
while($row=mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($switch_name_temp,$row['switch_name'] );
array_push($token_temp,$row['token'] );
// $options=array_merge($options,array($row['switch_name'] => $row['token'])); 因$row['switch_name']可能为数字,不能用。
}
$options=array();
$options=array_combine($switch_name_temp,$token_temp);
return $options;
}
?>


这个函数将一个或多个数组的单元合并起来,一个数组中的值附加在前一个数组的后面。返回作为结果的数组。

如果输入的数组中有相同的字符串键名,则该键名后面的值将覆盖前一个值。然而,如果数组包含数字键名,后面的值将不会覆盖原来的值,而是附加到后面。
http://justcoding.iteye.com/blog/1181962/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: