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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大