array("msg1"=>"asdasd","msg2"=>"dasdsa"));/*----------如何将一个数据添加到数">
当前位置:Gxlcms > PHP教程 > php对多维数组的操作,该怎么解决

php对多维数组的操作,该怎么解决

时间:2021-07-01 10:21:17 帮助过:21人阅读

php 对多维数组的操作
我想将数据循环插入多维数组,请问该怎么做?
代码如下:

$a=array("date"=>array
(
"msg1"=>"asdasd",
"msg2"=>"dasdsa")
);
/*----------如何将一个数据添加到数组中,使数组
输出如下---------------------*/
/* Array ( [date] => Array ( [msg1] => asdasd [msg2] => dasdsa[msg3] => dasdsa[msg4] => dasdsa ) ) */

我用了array_push函数,可是结果不是我想要的。
代码如下:

$a=array("date"=>array("msg1"=>"asdasd","msg2"=>"dasdsa"));
array_push($a['date'],array('msg3'=>'tel'));
print_r($a);

输出结果是
Array ( [date] => Array ( [msg1] => asdasd [msg2] => dasdsa [0] => Array ( [msg3] => tel ) ) )
但我想要的是Array ( [date] => Array ( [msg1] => asdasd [msg2] => dasdsa [msg3] => tel ) )
请问如何才能做到?求大神帮忙。
急需!!!
------解决方案--------------------

$a=array();
foreach($data as $k=>$v){
$a['date']['msg'.$k]=$v;
}
print_r($a);

------解决方案--------------------
$a=array("date"=>array("msg1"=>"asdasd","msg2"=>"dasdsa"));
$a['date']['msg3'] = 'tel';
print_r($a);
Array
(
[date] => Array
(
[msg1] => asdasd
[msg2] => dasdsa
[msg3] => tel
)

)


------解决方案--------------------

$a=array("date"=>array("msg1"=>"asdasd","msg2"=>"dasdsa"));
$a['date']['msg3'] = 'tel';
print_r($a);



Array
(
[date] => Array
(
[msg1] => asdasd
[msg2] => dasdsa
[msg3] => tel
)

)

------解决方案--------------------
$a=array("date"=>array("msg1"=>"asdasd","msg2"=>"dasdsa"));
$a = array_merge_recursive($a, array('date' => array('msg3'=>'tel')));
print_r($a);
Array
(
[date] => Array
(
[msg1] => asdasd
[msg2] => dasdsa
[msg3] => tel
)

)

人气教程排行