douxie2029 2012-04-20 13:11
浏览 42
已采纳

使用array_merge_recursive将数组合并在一起,但之后只将新内容添加到数组中?

If you found the title misleading, sorry. I couldn't really come up with a good title for this question.

I have two arrays, that I'm merging together in a function:

$arr1['something']['secondary_something'][]="foo1";
$arr1['something']['secondary_something'][]="foo2";
$arr1['something']['secondary_something'][]="foo3";

$arr2['something']['secondary_something'][]="foo4";
$arr2['something']['secondary_something'][]="foo5";

function something($array_, $array_new) {

$array=array_merge_recursive($array_,$array_new); // to combine/merge both arrays

print_r($array);//debugg

}

Now that function simply prints this (which is all good):

Array ( [something] => Array ( [secondary_something] => Array ( [0] => foo1 [1] => foo2 [2] => foo3 [3] => foo4 [4] => foo5 ) ) )

But I need to work with the new data, that has been merged to the primary array. So I need to work $arr2, but only once it has been merged with $arr1.

When I say I need to "work with the new data", var_export() is one of the things I need to do with the array.

If I simply do a echo var_export($array_new,true);, I get this:

array ( 'something' => array ( 'secondary_something' => array ( 0 => 'foo4', 1 => 'foo5', ), ), )

When I need this:

array ( 'something' => array ( 'secondary_something' => array ( 3 => 'foo4', 4 => 'foo5', ), ), )

^^ Notice how the array keys are 3 and 4, not 1 and 2. Because it has been merged with the primary array ($arr1).

Hope you guys understand what I'm trying to do.

Any ideas?

Thanks xD

  • 写回答

1条回答 默认 最新

  • dongluan1901 2012-04-20 13:18
    关注
    echo var_export(array_intersect($array['something']['secondary_something'], $arr2['something']['secondary_something']), true);
    

    EDIT This works, but you lose the multidimensional aspect of the array. You'll need to write a recursive function to step through the entire array if you want to preserve the something and secondary_something aspect in your var_export

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?