dongyixiu3110 2011-10-13 20:56
浏览 29
已采纳

什么PHP代码模拟array_merge_recusive的行为?

I am trying to do something like instead of using array_merge_recusive in php

<?php
$A = array("EUR"=>10);
$B = array("EUR"=>10,"JPY"=>20);    
$C = $A;
foreach ($B as $key => $value) {
    if (!isset($C[$key])) {
        $C[$key][] = array();
    } 
     $C[$key] = $value;

}

var_dump($C);

array(2) {
  ["EUR"]=>
  int(10)
  ["JPY"]=>
  int(20)
}

I need to get like this:

array(2) {
  ["EUR"]=>array(10,10),
  ["JPY"]=> int(20)
}

EDIT

Check code I am trying here http://codepad.org/x4MuYCiH What I did wrong ,I could not get the expected result?

thanks

  • 写回答

3条回答 默认 最新

  • douxuanwei1980 2011-10-13 21:40
    关注

    For the solution see this paste: http://codepad.org/60IKweVu. I also show the code at the bottom of this answer. This solution is based on the example data in your previous question about this array merge and total if it the same keys.

    Note that

    array(2) {
      ["EUR"]=>array(10,10),
      ["JPY"]=> int(20)
    }
    

    is equivalent to

    array(2) {
      ["EUR"]=> array([0] => 10, [1] => 10),
      ["JPY"]=> int(20)
    }
    

    but that the first notation simply does not show the keys of the nested array.

    CODE:

    <?php
    $A = array("EUR"=>10,"USD"=>20);
    $B = array("EUR"=>10,"JPY"=>20);
    
    $C = array_merge_recursive($A, $B);
    var_dump($C);
    
    //
    // This emulates the array_merge_recursive call
    //
    $C = array();
    $allArrays = array($A, $B);
    foreach($allArrays as $array) {
        foreach ($array as $key => $value) {
            if (! isset($C[$key])) {
                $C[$key] = array();
            }
            $C[$key][] = $value;
        }
    }
    
    foreach ($C as $index => $values) {
        if (count($values) == 1) {
            $C[$index] = $values[0];
        }
    }
    
    var_dump($C);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分