【发布时间】:2020-01-28 22:29:56
【问题描述】:
我遇到了问题,无法解决。
// get list of categories
$terms = $listing->get_field( 'region' );
foreach($terms as $t){
$parent_category = mg_get_term_parents( $t->term_id, 'region' );
}
当我转储 parent_category 时,我得到一个数组(它只打印祖父母和父母),子代码位于底部。
array(2) {
[0]=>
object(WP_Term)#6446 (10) {
["term_id"]=>
int(213)
["name"]=>
string(8) "Americas"
["slug"]=>
string(8) "americas"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(213)
["taxonomy"]=>
string(6) "region"
}
[1]=>
object(WP_Term)#6448 (10) {
["term_id"]=>
int(157)
["name"]=>
string(13) "United States"
["slug"]=>
string(13) "united-states"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(157)
["taxonomy"]=>
string(6) "region"
}
}
或者如果祖父母没有出现,我会得到一个数组。
object(WP_Term)#6454 (10) {
["term_id"]=>
int(214)
["name"]=>
string(4) "EMEA"
["slug"]=>
string(4) "emea"
["term_group"]=>
int(0)
["term_taxonomy_id"]=>
int(214)
["taxonomy"]=>
string(6) "region"
}
如果我只有父母和孩子,我使用以下方法,它给了我很好的结果。但不确定需要在此处添加什么以涵盖所有情况。
foreach( $terms as $t )
{
if ( $parent_category = mg_get_term_parents( $t->term_id, 'region' ) )
{
array_unshift( $terms, $parent_category );
}
}
$formatted_terms = array_filter( array_map( function( $term ) {
if ( ! $term = \MyListing\Src\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
'text_color' => $term->get_text_color(),
'icon' => $term->get_icon( [ 'background' => false, 'color' => false] ),
];
}, $terms ) );
当我有祖父母、父母和孩子时,就会出现问题。上面的解决方案不起作用。
如果我使用
$formatted_terms = array_filter( array_map( function( $term ) {
if ( ! $term = \MyListing\Src\Term::get( $term ) ) {
return false;
}
return [
'link' => $term->get_link(),
'name' => $term->get_name(),
'color' => $term->get_color(),
'text_color' => $term->get_text_color(),
'icon' => $term->get_icon( [ 'background' => false, 'color' => false] ),
];
}, $terms ) );
我只打印数组中的 1 个区域,而缺少的区域是一个孩子。数组仅输出父母和祖父母。我需要以某种方式将数组输出添加到上面的代码中 tog et all required.
知道如何做到这一点吗?
【问题讨论】: