2010-05-20 73 views

回答

5

array_replace_recursive PHP的文檔頁面,有人張貼了下面的源代碼來代替它的使用方法:

<?php 
if (!function_exists('array_replace_recursive')) 
{ 
    function array_replace_recursive($array, $array1) 
    { 
    function recurse($array, $array1) 
    { 
     foreach ($array1 as $key => $value) 
     { 
     // create new key in $array, if it is empty or not an array 
     if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key]))) 
     { 
      $array[$key] = array(); 
     } 

     // overwrite the value in the base array 
     if (is_array($value)) 
     { 
      $value = recurse($array[$key], $value); 
     } 
     $array[$key] = $value; 
     } 
     return $array; 
    } 

    // handle the arguments, merge one by one 
    $args = func_get_args(); 
    $array = $args[0]; 
    if (!is_array($array)) 
    { 
     return $array; 
    } 
    for ($i = 1; $i < count($args); $i++) 
    { 
     if (is_array($args[$i])) 
     { 
     $array = recurse($array, $args[$i]); 
     } 
    } 
    return $array; 
    } 
} 
?> 
+1

當使用功能不止一次,我得到:致命錯誤:不能重新聲明遞歸() – mikewasmike 2015-03-12 08:36:15

1

通過@Justin上面的代碼就可以了,節省了兩件事情:

  1. 函數在php執行開始時不易獲取,因爲它被包裝在if()中。 PHP docu

    When a function is defined in a conditional manner such as the two examples shown. Its definition must be processed prior to being called.

  2. 最重要的是;調用該函數兩次會導致致命錯誤。 PHP docu

    All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.

所以我只是外面array_replace_recursive功能移動recurse功能,效果不錯。我也刪除了if()條件,並更名爲array_replace_recursive_b4php53害怕今後的upgradings

+0

這應該是對Justin的答案評論(由於篇幅在評論中是有限的,你可以在鏈接中發佈完整的消息)。標記爲這不是一個答案。 – mickmackusa 2017-04-30 15:45:32