2010-01-12 25 views
2

所以我猜想從文本文件動態地構建一個多維數組,一切完美的作品,除了數字鍵都在擰我...PHP array_merge_recursive用數字鍵

的文本文件看起來像這樣的:

a=1 
b.c=2 
b.d.0.e=3 
b.d.0.f=4 
b.d.1.e=5 
b.d.1.f=6 

由於array_merge_recursive不與數字鍵工作,輸出類似:

array(2) { 
["a"]=> 
string(3) "1" 
["b"]=> 
array(2) { 
    ["c"]=> 
    string(3) "2" 
    ["d"]=> 
    array(4) { 
    [0]=> 
    array(1) { 
    ["e"]=> 
    string(9) "3" 
    } 
    [1]=> 
    array(1) { 
    ["f"]=> 
    string(4) "4" 
    } 
    [2]=> array(1) { 
    ["e"]=> 
    string(8) "5" 
    } 
    [3]=> 
    array(1) { 
    ["f"]=> 
    string(9) "6" 
}}}} 

有沒有簡單的解決方案,使輸出像...?

array(2) { 
["a"]=> 
string(3) "1" 
["b"]=> 
array(2) { 
    ["c"]=> 
    string(3) "2" 
    ["d"]=> 
    array(2) { 
    [0]=> 
    array(2) { 
    ["e"]=> 
    string(9) "3" 
    ["f"]=> 
    string(4) "4" 
    } 
    [1]=> 
    array(3) { 
    ["e"]=> 
    string(9) "5" 
    ["f"]=> 
    string(4) "6" 
}}}} 

感謝

+0

答案中的任何解決方案都可以工作,但我建議任何人存儲這樣的數據,這樣做會更合適(例如,使用json字符串)。 – GZipp 2010-01-12 15:15:24

回答

3

你可以每一位闖入其組件,並建立在一個時間數組中的一個步驟。

$path = "b.d.0.e"; 
$val = 3; 
$output = array(); 

$parts = explode(".", $path); 

// store a pointer to where we currently are in the array. 
$curr =& $output; 

// loop through up to the second last $part 
for ($i = 0, $l = count($parts); $i < $l - 1; ++$i) { 
    $part = $parts[$i]; 

    // convert numeric strings into integers 
    if (is_numeric($part)) { 
     $part = (int) $part; 
    } 

    // if we haven't visited here before, make an array 
    if (!isset($curr[$part])) { 
     $curr[$part] = array(); 
    } 

    // jump to the next step 
    $curr =& $curr[$part]; 
} 

// finally set the value 
$curr[$parts[$l - 1]] = $val; 

我的輸出,使用相同的輸入和你:

Array (
    [a] => 1 
    [b] => Array (
     [c] => 2 
     [d] => Array (
      [0] => Array (
       [e] => 3 
       [f] => 4 
      ) 
      [1] => Array (
       [g] => 5 
       [h] => 6 
      ) 
     ) 
    ) 
) 
+0

感謝您的回答:) if(is_numeric)雖然不是必需的,但我認爲它已經將var解釋爲int。 – 2010-01-12 15:40:59

0

或者你可以使用eval()

$raw_data = file($txt_file, FILE_IGNORE_NEW_LINES); 
foreach ($raw_data as $line) { 
    list($keys, $value) = explode('=', $line); 
    $keys = explode('.', $keys); 
    $arr_str = '$result'; 
    foreach ($keys as $key) { 
     if (ctype_digit($key)) { 
      $arr_str .= "[" . $key . "]"; 
     } else { 
      $arr_str .= "['" . $key . "']"; 
     } 
    } 
    eval($arr_str . ' = $value;'); 
} 

print_r($result); 
0

我知道這是一個古老的,但最好的解決方案我已經發現是使用array_replace_recursive。它會實現你想要做的事情:

$start = array(
    "600" => array("total" => 100), 
    "700" => array("total" => 200) 
); 

$finish = array(
    "600" => array("average" => 25), 
    "700" => array("average" => 50) 
); 

$out = array_replace_recursive($start,$finish); 
var_dump($out): 

array(2) { 
    [600]=> 
    array(2) { 
    ["total"]=> 
    int(100) 
    ["average"]=> 
    int(25) 
    } 
    [700]=> 
    array(2) { 
    ["total"]=> 
    int(200) 
    ["average"]=> 
    int(50) 
    } 
}