查找并添加到未知多维数组中的关联数组



我正在尝试通过向数组添加数组来创建自我填充树。我遇到的问题是在数组中找到一个关联键,然后向其添加新内容(一个新数组(。

如何解决此问题?

这可以递

归完成。您可以在主数组中搜索键,并将该值与要追加/插入的数据合并。

下面我创建了两个可以实现此目的的函数。

/** Append or create to an array searching for the index with the with the value $key. If $key is set to null, append to array using numerical index.
 * @param array $masterArray Array to append to
 * @param mixed $data
 * @param null  $key         If not set, will append to the master array
 */
function append($key, $data, &$masterArray) {
    if($key===null) {
        $masterArray[] = $data;
    } else if(!_appendHelper($key, $data, $masterArray)) {
        $masterArray[$key] = $data;
    }
}
/** Helper function to recursively search/merge array */
function _appendHelper($key, $data, &$masterArray) {
    foreach($masterArray as $k => &$v) {
        if($k===$key) {
            $v = array_merge($v, is_array($data) ? $data : [$data]);
            return true;
        } elseif(is_array($v)) {
            _appendHelper($key, $data, $v);
        }
    }
    return false; // Key does not exist
}

$masterArray = ['foo' => ['bar' => ['ram' => ['ewe' => []]]], ['man' => ['chu' => []]]];
append('foo', ['__TEST1__' => [1, 1, 1]], $masterArray);
print_r($masterArray);
append('new_key', ['__TEST2__' => [2, 2, 2]], $masterArray);
print_r($masterArray);
append(null, ['__TEST3__' => [3, 3, 3]], $masterArray);
print_r($masterArray);