2011-12-16 59 views
0

我完全被困在看似微不足道的問題上。php函數返回空字符串。 echo正確地打印字符串;

我有這樣的功能:

function findCategoryNameInTree($id, $tree) { 
    foreach($tree as $branch) { 
     if ($branch['category_id'] == $id) { 
      echo $branch['name'];//works 
      print_r($branch['name']);//works 
      //return($branch['name']); //returns nothing 
      return $branch['name'];//fix this line per feedback still no return value 
     } else { 
      if(count($branch['children']) > 0) { 
       findCategoryNameInTree($id,$branch['children']); 
      } 
     } 

    } 
} 

我想不出我爲什麼它不返回任何東西的生活。

請幫忙!

編輯 以下是我打電話給我的功能

//what I really want to do 
$primgenre = findCategoryNameInTree($cat_id,$category_tree['children']); 

//but this doesnt work either 
echo $primgenre; 

//nor this 
print_r($pringenre); 
+3

你沒告訴我們這塊調用你的`findCategoryNameInTree`功能的代碼和它是如何你確定函數的返回值是錯誤的,而不是你對函數返回值的解釋。 – 2011-12-16 17:13:19

回答

1

您流連忘返此: -

findCategoryNameInTree($id,$branch['children']); 

變化: -

return findCategoryNameInTree($id,$branch['children']); 
0

只是刪除圓括號,然後它應該工作!?

return $branch['name']; 

感謝負;)

如果你的函數可以作爲你說的地步,呼籲

$test = findCategoryNameInTree(XY, "bla"); 
echo $test; 

應該輸出什麼。

+0

它並不重要 – matino 2011-12-16 17:16:02

+0

當您通過參考返回時,事情並不重要,所以最好始終保持關閉狀態。 – Maerlyn 2011-12-16 17:17:39

+1

參考:http://php.net/manual/en/function.return.php – diEcho 2011-12-16 17:25:02

0

試試這個:

function findCategoryNameInTree($id, $tree) { 
foreach($tree as $branch) { 
    if ($branch['category_id'] == $id) { 
     x = $branch['name']; 
    } else { 
     if(count($branch['children']) > 0) { 
      findCategoryNameInTree($id,$branch['children']); 
     } 
    } 

} 
return x; 

}

1

here明確提到

當返回一個數組,你應該 返回之前聲明數組,否則的結果是不是你期望;

另請注意

你不應該使用括號返回變量返回時,通過參考 ,因爲這將無法正常工作。您只能通過引用返回 變量,而不是語句的結果。

foreach($tree as $branch) { } 

這裏$branch只是陣列的內部指針(假定作爲參考)的$tree

0

這適用於我,也適用於$ my_result方式!

<?php 

$tree = ARRAY(); 
$tree[0] = ARRAY('category_id'=>10, 'name'=>'ten', 'children'=>''); 
$tree[1] = ARRAY('category_id'=>11, 'name'=>'eleven', 'children'=>''); 
$tree[2] = ARRAY('category_id'=>12, 'name'=>'twelve', 'children'=>''); 


function findCategoryNameInTree($id, $tree) { 
    //$my_result = 'none'; 
    foreach($tree as $branch) { 
    if ($branch['category_id'] === $id) { 
     //echo $branch['name'];//works 
     //print_r($branch['name']);//works 
     //$my_result = $branch['name']; 
     //break; 
     return $branch['name']; //returns nothing 
    } 
    //else { 
    // if(count($branch['children']) > 0) { 
    // findCategoryNameInTree($id,$branch['children']); 
    // } 
    //} 
    } 
    //return $my_result; 
} 

echo findCategoryNameInTree(10, $tree).'<br />'; 
echo findCategoryNameInTree(11, $tree).'<br />'; 
echo findCategoryNameInTree(12, $tree).'<br />'; 

?> 
0

試試這個方法:

$primgenre = findCategoryNameInTree($cat_id,$category_tree); 

$分公司是(應該是)一個數組,所以$樹(應該是)。如果$ tree數組包含格式良好的$ branch數組,那麼一切都應該正常工作。用我的示例$ tree數組查看我的其他解決方案。