哪些PHP代码可以模拟array_merge_recusive的行为? [英] What PHP code emulates the behaviour of array_merge_recusive?

查看:42
本文介绍了哪些PHP代码可以模拟array_merge_recusive的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做类似的事情,而不是在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)
}

我需要这样:

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

编辑

我在这里尝试检查代码 http://codepad.org/x4MuYCiH 我做错了,我没有得到预期的结果?

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

谢谢

推荐答案

有关解决方案,请参见以下粘贴: http://codepad.org/60IKweVu .我还在此答案的底部显示了代码.此解决方案基于上一个问题中有关此的示例数据数组合并和总计(如果它们具有相同的键).

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.

请注意

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

等同于

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.

代码:

<?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);

这篇关于哪些PHP代码可以模拟array_merge_recusive的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆