$array1 = [ "month" => "Jan", "count" => "20" , "month" => "feb", "count" => "2" ];
$array2 = [ "month" => "Jan", "count" => "50" , "month" => "feb", "count" => "27" ];
合并上述2个数组后的预期数组
$fianlarray = ["month" => "jan" , "count"=>"20" , "count" => "50" ,
"month" => "feb" , "count" => "2", "count" => "27" ];
我已尝试过array_merge和union但没有结果。提前谢谢
答案 0 :(得分:2)
我认为存储数据存在问题。你不能在同一级别的数组内使用相同的密钥两次,这将导致覆盖旧数据。
$ array1 = [" month" => " Jan"," count" => " 20" ,"月" => " feb"," count" => " 2" ]。 $ array2 = [" month" => " Jan"," count" => " 50" ,"月" => " feb"," count" => " 27" ];
在您的代码中,您正在存储' month'作为' jan'然后'月'如同' feb',这会覆盖之前的“月份”分配。 => '扬'
请重新构建在数组中存储信息的方式。
如果需要更多帮助,我很乐意提供帮助。
谢谢,Happy Coding。
答案 1 :(得分:1)
不幸的是,我们无法按照您在问题中提到的那样做,您不能再使用相同的关联键,在这种情况下,重复的关联键会覆盖值
$fianlarray = ["month" => "jan" , "count"=>"20" , "count" => "50" ,
"month" => "feb" , "count" => "2", "count" => "27" ];
我建议你做好像下面这样的结构
$fianlarray = [["month" => "jan" , "count"=>["20", "50"]],
["month" => "feb" , "count" => ["2","27"]]];
OR
$fianlarray = ["jan"=>["20", "50"],"feb"=>["2","27"]];
答案 2 :(得分:1)
@Aravindh Gopi你不能得到你想要的数组,因为数组可以 没有相同的名称索引多于一个,如果你这样做这样的数组 将覆盖这些值,在这种情况下,$ array1值将结束 由$ array2值编写,你将得到你的最终数组:
$ fianlarray = [" month" => "二月&#34 ;, "计数" => " 27" ];
但是如果你想要你的解决方案所以你可以使用函数array_merge_recursive()来完成它,这个函数将为你提供你的解决方案,但是你将在一个新的数组中获得相同的索引值,其中0和1索引尝试低于一:
<?php
$array1 = [ "month" => "Jan", "count" => "20"];
$array2 = ["month" => "feb", "count" => "27" ];
$fianlarray=array_merge_recursive($array1,$array2);
print_r($fianlarray);
?>
OutPut将是:
数组([month] =&gt;数组([0] =&gt; Jan [1] =&gt; feb)[count] =&gt;数组( [0] =&gt; 20 [1] =&gt; 27))
因此,如果你需要这个(y)
,请尝试答案 3 :(得分:0)
你做不到这样的事情:
$fianlarray = ["month" => "jan" , "count"=>"20" , "count" => "50" ,
"month" => "feb" , "count" => "2", "count" => "27" ];
这里你定义了多次“月”,“计数”,这是禁止的......