0

我做了一個小函數來解析和獲取來自多維數組的元素,其中使用類Unix語言的路徑語法編寫的字符串。PHP - 丟失函數中的數組引用(本地到全局)

function array_get($path, &$array) { 
    $keys = preg_split('/[\/\\\]+/', $path, null, PREG_SPLIT_NO_EMPTY); 
    $current = trim(array_shift($keys)); 
    if (is_array($array) && array_key_exists($current, $array)) { 
     $path = implode("/", $keys); 
     if (empty($path)) { 
      // (Place the code here, see below) 
      return $array[$current]; 
     } 
     return array_get($path, $array[$current]); 
    } 
    return false; 
} 

所以,如果我有一個簡單的數組像這樣

$arr = array(
    "A" => array(
     "X" => array(), 
     "Y" => array(), 
     "Z" => array() 
    ), 
    "B" => array(
     "X" => array(), 
     "Y" => array(), 
     "Z" => array() 
    ), 
    "C" => array(
     "X" => array(), 
     "Y" => array(), 
     "Z" => array() 
    ) 
); 

,我想某些條目內填充它像這些

$arr['A']['Z'][] = "foo"; 
$arr['A']['Z'][] = "bar"; 

我會用做同樣的工作如下聲明:

$var = array_get("A/Z", $arr); 
$var[] = "foo"; 
$var[] = "bar"; 

但出了點問題。

如果您嘗試運行代碼,您會注意到超出本地範圍對傳遞數組的引用將會丟失。

如果你想運行一個測試,你可以替換佔位符註釋行與這兩個行代碼的函數內:

  $array[$current][] = "foo"; 
      $array[$current][] = "bar"; 

然後你會看到該功能實際上執行自己的任務。

有沒有辦法讓保持引用的輸出?

+0

是的,有這樣[方法](https://eval.in/98153)。 – raina77ow

回答

1

the documentation開始,您可以指定要使用函數名稱函數調用之前的&字符返回參考。

<?php 

function &foo(&$arr) { 
    return $arr[0]; 
} 

$a = [[]]; 
$b = &foo($a); 
$b[0] = 'bar'; 
print_r($a); /* outputs [ [ 'bar' ] ] */ 
+1

爲了擴大這個答案,你對'array_get'的調用必須使用參考分配。這包括它的內部遞歸調用。 但是,向'return foo()'添加'&'將導致語法錯誤。所以你必須把它分配給一個變量,然後返回變量。 – Sean

+0

它就像一個魅力!非常感謝。 – Galileo

0

您可以return references

但是我覺得你的方法真的很麻煩,很快就會導致不正確的行爲/可維護性/可讀性問題。