为什么print_r和返回返回不同的值


Why are print_r and return returning different values?

我在PHP/Wordpress中有以下自定义函数。

function GetAncestors($post_id, $ancestors = array()) {
    $query = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $term_data = RunQuery($query)[0];
    array_push($ancestors,$term_data);
    if($term_data[parent]!='11') GetAncestors($term_data[parent],$ancestors);
    else print_r($ancestors);
    //else return $ancestors;
}

如果我print_r数组,它会返回预期的结果。如果我return数组的值并将其print_r函数外部(这就是我想做的),它会返回一个空白字符串。

print_r结果:

Array ( [0] => Array ( [term_id] => 95 [name] => PDR (Appraisals) [parent] => 91 ) [1] => Array ( [term_id] => 91 [name] => Your career, learning and development [parent] => 14 ) [2] => Array ( [term_id] => 14 [name] => You At ... [parent] => 11 ) ) 

这是为什么呢?

不应该是这样的:

// Changed ancestors to reference
// Changed constant 'parent' to string
function GetAncestors($post_id, &$ancestors = array()) {
    $query = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $term_data = RunQuery($query)[0];
    array_push($ancestors,$term_data);
    if($term_data['parent']!='11') {
        GetAncestors($term_data['parent'],$ancestors);
    }
}
$ancestors = array();
GetAncestors($id, $ancestors);
print_r($ancestors);

就个人而言,为了实用性,我会这样写:

function GetAncestors($post_id, &$ancestors = null) {
    if (null === $ancestors) {
        $ancestors = array();
    }
    $query  = 'SELECT `wp_terms`.term_id, `wp_terms`.name, `wp_term_taxonomy`.parent FROM `wp_terms` LEFT JOIN `wp_term_taxonomy` ON `wp_terms`.term_id = `wp_term_taxonomy`.term_id WHERE `wp_terms`.term_id = '.$post_id;
    $result = RunQuery($query);
    if (count($result) > 0) {
        $count = 1;
        $term_data = $result[0];
        array_push($ancestors,$term_data);
        if($term_data['parent']!='11') {
            $count += GetAncestors($term_data['parent'],$ancestors);
        }
        return $count;
    }
    return 0;
}
if (GetAncestors($id, $ancestors) > 0) {
    print_r($ancestors);
}

使用返回标志:

print_r($ancestors, true);

来自 php 文档: http://php.net/manual/en/function.print-r.php

如果要捕获 print_r() 的输出,请使用返回 参数。当此参数设置为 TRUE 时,print_r() 将返回 信息而不是打印它。