0

我有一个像这样的数组:

> Array
> (
>>    [trilha] => 1
>>    [0] => Array
>>>        (
>>>            [trilha] => 1,5
>>>            )
> )

我想与关键 TRILHA 交叉,插入相关值:

> Array
> (
>> [1] => A 
>> [1,5] => B
>> [1,5,4] => C
> )

可能吗?

结果应该是:

> Array
> (
>>    [trilha] => 1
>>    [INSERTED] => A
>>    [0] => Array
>>>        (
>>>            [trilha] => 1,5
>>>            [INSERTED] => B
>>>            )
> )

我将辅助数组中的值插入到第一个数组中。

4

1 回答 1

0

一些工作示例,基于堆栈的递归迭代和使用 PHP 变量别名的修改:

// to be modified:
$base = array(
    'trilha' => '1',
    array(
        'trilha' => '1,5',
    ),
);

// data for modification, binding value is key
$insert = Array(
    1 => 'A',
    '1,5' => 'B',
    '1,5,4' => 'C',
);

/*
 * stack based traversal and modifcation
 */
$stack = array();
$stack[] = &$base;
$first = 0;
while ($stack)
{
    $proc = & $stack[$first];
    unset($stack[$first++]);

    foreach ($proc as &$val) {
        if (is_array($val)) {
            $stack[] = &$val;
        }
    }

    if (!isset($proc['trilha'])) {
        continue;
    }
    $trilha = $proc['trilha'];
    if (!isset($insert[$trilha])) {
        continue;
    }
    $proc['INSERTED'] = $insert[$trilha];
}
unset($proc);

var_dump($base);
于 2012-04-17T00:55:29.760 回答