2015-12-17 119 views
0

大家好!數組:如何返回參考/指針

如何返回函數中的數組引用/指針?

例如:

$a=array('given'=>array()); 

function getRef(&$ref){ 

//adds a child element to the given reference/pointer 
$ref['test']=array(); 

//doesn't return the current reference/pointer 
return $ref['test']; 
} 

//out: Array ([given] => Array ([test] => Array ())) 
$p=getRef($a['given']); 
print_r($a); 

//out: same as above 
//expected: ([given] => Array ([test] => Array ([test2] => Array ()))) 
$p['test2']=array(); 
print_r($a); 

謝謝!

+0

檢查下面的工作:) – Gogul

回答

0

也許是這樣的:

$a=array('given'=>array()); 

function getRef(&$ref){ 

//adds a child element to the given reference/pointer 
$ref['test']=array(); 

//doesn't return the current reference/pointer 
return $ref['test']; 
} 

//out: Array ([given] => Array ([test] => Array ())) 
$p=getRef($a['given']); 
print_r($a); 

//out: same as above 
//expected: ([given] => Array ([test] => Array ([test2] => Array ()))) 
$p['given']['test']['test2']=array(); 
print_r($p); 
1

試試這個

<?php 
$a=array('given'=>array()); 

function &getRef(&$ref){ 

//adds a child element to the given reference/pointer 
$ref['test']=array(); 

//doesn't return the current reference/pointer 
return $ref['test']; 
} 

//out: Array ([given] => Array ([test] => Array ())) 
$p=&getRef($a['given']); 
print_r($a); 

//out: same as above 
//expected: ([given] => Array ([test] => Array ([test2] => Array ()))) 
$p['test2']=array(); 
print_r($a); 
?> 
+0

如果你發現這個標記是正確的,那麼這將被標記爲已解決 – Gogul

+1

爲什麼OP應該「試試這個」?一個好的答案***將總是解釋所做的事情以及爲什麼這樣做,不僅是爲了OP,而且是爲了將來SO的訪問者。 –

0

當你通過引用傳遞使用相同的變量函數內部,你做的外面,你不回一個值。 PHP Manual - Passing by Reference

$a = array('given' => array()); 

function getRef(&$a) 
{ 
    $a['test']=array(); 
} 

// this now has the nested array test. 
getRef($a['given']); 
print_r($a); 

如果這是你所有的功能是做那麼我會建議只設置這些嵌套陣列正常。

$b = ['given' => ['test' => ['test2' => []]]]; 
print_r($b); 
1
function &getRef(&$ref){ 

return $ref['test']; 

通過使用在函數開始的符號,你返回varible而不是價值的REFFERENCE。