0

再帰関数を作成しました。必要なのは、その製品の親カテゴリの説明と term_id を取得することです。

function desc_pro($parent) {
    $term = get_term_by('parent', $parent, 'product_cat');
    $description = $term->description;

    while($description == null) {
        $desc = desc_pro($term->parent);
        return $desc;
    }
    return $description;
}

このコードを実行すると、正しい説明が表示されます。しかし、リターンのいずれかを削除すると、機能しません。空白を示しています。(これでいい?コードが間違っていると思う?)

2 番目: term_id が必要です。配列を作成すると、すべてのサブカテゴリ ID も送信されます。これは間違っています。説明があるIDだけが必要です。

コードが間違っていると思いますか?それとも他に問題がありますか?

これは私の配列です: (私が送信するのは、私のphpページからの親カテゴリです。したがって、関数 get_desc(48); を呼び出します)

それは私に最初のオブジェクトを与えます、今私は説明が利用可能かどうかをテストしなければなりませんか? はいの場合は、停止して説明と term_id を返します。利用できない場合は、親 ID を取得して再度確認してください。したがって、これは説明が見つかるまで続きます。

stdClass Object
(
    [term_id] => 48
    [name] => Cereal
    [slug] => cereal
    [term_group] => 0
    [term_taxonomy_id] => 49
    [taxonomy] => product_cat
    [description] => 
    [parent] => 46
    [count] => 0
)

stdClass Object
(
    [term_id] => 46
    [name] => Grocery Store A
    [slug] => grocery-store-a
    [term_group] => 0
    [term_taxonomy_id] => 47
    [taxonomy] => product_cat
    [description] => FDIC, 17th Street Northwest, Washington, DC
    [parent] => 45
    [count] => 0
)
4

1 に答える 1

1

while ループは変更されません$descriptionが、基本ケースではなく、無限ループを作成した場合$descは常に変更されます。null

これを試して:

function desc_pro($parent) {
    $term = get_term_by('parent', $parent, 'product_cat');
    $description = $term->description;

    if( $description == null)
        return desc_pro($term->parent); // recurse if not set
        //$description = desc_pro($term->parent); // an alternative to the above

    return $description; // base case (when set)
}

リターンと割り当ての違いは、余分なリターンです。PHP はテール コールの最適化を行わないため、それほど違いはありませんが、コメント アウトされていない方が関数型プログラマーにとって見栄えがするだけです。

反復的なアプローチの場合、while ループが適しています。

function desc_pro($parent) {
    $description = null;

    while( $description == null) {
        $term = get_term_by('parent', $parent, 'product_cat');
        $description = $term->description;
    }

    return $description; // base case (when set)
}
于 2013-08-19T20:43:19.223 に答える