2016-12-10 63 views
0

我有帶數據的結構化數組,需要將附加數據附加到節點X.節點X由其他數組($ path)中的路徑指定。在樹中的某個特定位置包含新數據

$data = [ 
183013 => 
    [ 
     183014 => [ 
      183018, 
      183019 => [ 
       183021, 
       183022 => [ 
        183023 
       ] 
      ], 
      183020 
     ], 
     183016, 
     183017 
    ] 
]; 

$path = [183013, 183014, 183019, 183021]; 
$new_data = [183030 => [183031]]; 

所以,我需要$ NEW_DATA追加到元素183021. 的$深度數據或$路徑是無限的。

+0

所有的編號是唯一的,正確的? – RomanPerekhrest

+0

你可以嘗試通過搜索和使用array_push方法 – C2486

+0

我認爲這些數字不是唯一的 – EugenA

回答

1

有了一些時間對phplab.io/lab/iwnXI

打我創造了這個:

數據

<?php 
$data = [ 
    183013 => [ 
     183014 => [ 
      183018, 
      183019 => [ 
       183021, 
       183022 => [ 
        183023 
       ] 
      ], 
      183020 
     ], 
     183016, 
     183017 
    ] 
]; 

$path = [183013, 183014, 183019, 183021]; 

$new_data = [183030 => [183031]]; 

解決方案1 ​​ - 遞歸函數

提供數據功能,並且每個節點都將被添加。 我們需要以除去最終的數字值(即, '0 => 183020')

<?php function appendIntoArrayTree(array $source, array $path, array $values) { 
    $key = array_shift($path); 

    if (isset($source[$key]) && is_array($source[$key])) { 
     $source[$key] = appendIntoArrayTree($source[$key], $path, $values); 
    } 
    else { 
     // search if the current $path key exist as 'value' on the $source (i.e.: '0 => 183021') 
     if(!is_null($foundKey = array_search($key, $source))) { 
      unset($source[$foundKey]); 
     } 
     $source[$key] = $values; // final 
    } 

    return $source; 
} 

和輸出:

var_dump(appendIntoArrayTree($data, $path, $new_data)); 

解決方案2 - EVAL模式

這是一個特技,和我不鼓勵使用它(另外一些服務器不允許使用eval()

function appendIntoArrayTreeWithEval(array $source, array $path, array $values) { 
    $path_last = $path[count($path) - 1]; 
    $path_string = implode('', 
     array_map(function($v) { 
     return '[' . $v . ']'; 
     }, array_slice($path, 0, count($path) - 1)) 
    ); // Convert $path = ['a', 'b', 'c'] to string [a][b] (last 'c' not used) 

    $tmp = null; 
    eval('$tmp = isset($source' . $path_string . ') ? $source' . $path_string . ' : null;'); 
    if(is_null($tmp)) { 
     // $source[a][b] does not exists 
     eval('$source' . $path_string . '[' . $path_last . '] = $values;'); 
    } 
    else if(is_array($tmp)) { 
     if(!is_null($key = array_search($path_last, $tmp))) { 
      // key exists with 'numeric' array key value (0 =>, 1 =>, ...) 
      eval('unset($source' . $path_string . '[' . $key . ']);'); // remove 
     } 
     eval('$source' . $path_string . '[' . $path_last . '] = $values;'); 
    } else { 
     // is string/numeric/... Error. SHould not use 0/1/2 ... values 
    } 
    return $source; 
} 

和輸出

var_dump(appendIntoArrayTreeWithEval($data, $path, $new_data)); 

解決方案1是最好的:)

(我們也嘗試array merge recursive功能,但它不工作)

相關問題