为什么print_r并返回返回不同的值?

时间:2015-03-12 10:03:33

标签: php arrays wordpress function

我在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 ) ) 

为什么会这样?

2 个答案:

答案 0 :(得分:1)

不应该是这样的:

// 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);
}

答案 1 :(得分:0)

使用返回标志:

print_r($ancestors, true);

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

  

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