如何增量替换多维数组?

时间:2019-05-02 06:09:09

标签: php arrays

给出多维数组A和多维数组B。如果键B中存在键,则用数组B中的值替换或添加数组A中的值

public partial class MasterForm: Form
{
    public MasterForm()
    {
        InitializeComponent();
    }
}

所需的是public partial class item: MasterForm { }

2 个答案:

答案 0 :(得分:1)

这适用于您的情况:

/**
 * Modifies an array to recursively replace the values with another array
 * This function modifies the passed in array, and does not return anything
 * 
 * @param array $startArray Initial array, passed as reference and will be modified
 * @param array $replaceArray Array of values which will replace values in the $startArray
 */
function replaceRecursive(&$startArray, $replaceArray) {
    $keys = array_keys($replaceArray);
    foreach ($keys as $key) {
        if (isset($replaceArray[$key])) {
                // If this is another array recurse to replace inner values
            if (is_array($replaceArray[$key])) {

                // Create array key in startArray if it doesn't exist yet
                if (!is_array($startArray[$key])) {
                    $startArray[$key] = array();
                }

                replaceRecursive($startArray[$key], $replaceArray[$key]);
            }
            else {
                // Just replace the key
                $startArray[$key] = $replaceArray[$key];
            }
        }
    }
}

您可以使用如下方法:

$targetA = array(... some values ...);
$argumentB = array(... some values ...);
replaceRecursive($targetA, $argumentB);
var_dump($targetA);

如有任何疑问,请随时发表评论

答案 1 :(得分:0)

  /**
 * get path
 * @param $obj
 * @return array
 */
public function array_path($argumentB){
    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($argumentB), RecursiveIteratorIterator::SELF_FIRST);
    $paths = array();
    foreach ($iterator as $k => $v) {
        if (!$iterator->hasChildren()) {
            for ($p = array(), $i = 0, $z = $iterator->getDepth(); $i <= $z; $i++) {
                $p[] = $iterator->getSubIterator($i)->key();
            }
            $paths[] = $p;
        }
    }
    return $paths;
}


/**
 * get value of b
 * @param $path
 * @param $array
 * @return mixed
 */
public function get($path, $array) {
    $temp =& $array;
    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    return $temp;
}

/**
 * set value to A
 * @param $path
 * @param array $array
 * @param null $value
 */
public function set($path, &$array=array(), $value=null) {
    //$path = explode('.', $path); //if needed
    $temp =& $array;

    foreach($path as $key) {
        $temp =& $temp[$key];
    }
    $temp = $value;
}

/**
 * main func
 * @param $argumentB
 * @return mixed
 */
public function resetting($argumentB){
    $paths=$this->array_path($argumentB);
    $targetA=include $this->config_file;
    foreach($paths as $v){
        $this->set($v,$config,$this->get($v,$argumentB));
    }
    return $targetA;
}