ホームページ >バックエンド開発 >PHPチュートリアル >関数のパラメータが配列の場合、値による受け渡しとアドレスによる受け渡しの違いについて、専門家の方は例を挙げて説明してください。
05ce6a64733b2d7b67a9eac9cb90e57a 配列 ( [id] => 27 [子] => 配列 ( [0] => 配列 ( [id] => 30 [子] => 配列( [0] => 配列 ( [id] => 31 ) ) ) ) ) [1] => 配列 ( [id] => 28 [children] => 配列 ( [0] =>配列 ( [id] => 29 ) ) ) [2] => 配列 ( [id] => 32 ) )
配列 ( [0] => 配列 ( [id] => ; 27 [レベル] => 0 [親] => 0 ) [1] => 配列 ( [id] => 1 [親] => 27 ) => 配列 ( [id] => 31 [レベル] => 2 [親] => 30 ) [3] => 配列 ( [id] => 28 [レベル] => 0 [親] => 0 ) [4] => 配列 ( [id] => 29 [レベル] => 1 [親] => 28 ) [5] => 配列; 32 [レベル] => 0 [親] => 0 ) )
如果是样
function foo($ar, $level=0, $res=array ()) {
foreach($ar as $v) {
$t = array();
$v['レベル'] = $レベル;
$v['parent'] = $parent;
if(isset($v['children'])) {
$t = $v['子供'];
unset($v['children']);
} $res[] = $v;
if($t) foo($t, $level+1, $v['id'], $res);
}
$res;
}
結果 则:
配列( [0] => 配列 ( [id] => 27 [レベル] => 0 [親] => 0 ) [1] = > 配列 ( [id] => 28 [レベル] => 0 [親] => 0 ) [2] => 配列 ( [id] => 32 [レベル] => 0 [親] =>
逆承認(解決案)
参照伝達:
操作によって元のデータが変更されます。 2011/12/10/2283570.html
$res[] = $v;
if($t) foo($t, $level+1, $v['id'], $res)
----この这两个语句在関数数 foo ,ただし原理は一样的同じ楼上の例子
数组值传递实例代码:<?phpfunction main() { $cc = array( 'a','b' ); change($cc); var_dump($cc); die;}function change($cc){ $cc = array('dd');}main();?>output:array(2) { [0]=> string(1) "a" [1]=> string(1) "b"}数组引用传递<?phpfunction main() { $cc = array( 'a','b' ); change($cc); var_dump($cc); die;}function change(&$cc){ $cc = array('dd');}main();?>outpout:array(1) { [0]=> string(2) "dd"}
地址参照
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
传值
<?php$arr = array(1,2,3,4,5);pop($arr);print_r($arr);function pop(&$arr){ array_pop($arr);}?>
<?php$arr = array(1,2,3,4,5);$arr1 = pop($arr);print_r($arr);print_r($arr1);function pop($arr){ array_pop($arr); return $arr;}?>加上&就不会复制,而直接使用了