创建多维分类数组
大家好,我需要创建一个多维数组来通过javascript填充select。首先是两种分类法的选择,“store”和“state”。选择“存储”后,第二个选择将加载术语“状态”
我当前的查询是这样的。它工作得很好,但我需要用这些信息创建一个数组,有人能帮我吗?
$post_type = \'store\';
$tax = \'store_type\';
//$tax_terms = get_terms($tax);
$tax_terms = get_terms(\'store_type\');
if ( $tax_terms ) {
foreach ($tax_terms as $tax_term) {
$args = array(
\'post_type\' => $post_type,
"$tax" => $tax_term->slug,
\'post_status\' => \'publish\',
\'posts_per_page\' => -1,
\'orderby\' => \'title\',
\'order\' => \'ASC\',
);
$my_query = new WP_Query($args);
?>
<?php if ( $my_query->have_posts() ) : ?>
<?php $list = $tax_term->name;?>
<h2><?php echo $list; ?></h2> <!-- All store types are displayed -->
<ol>
<?php while ($my_query->have_posts()) : ?>
<?php $my_query->the_post(); ?>
<li>
<?php
$type_terms = wp_get_post_terms( $post->ID, \'state\');
if ( $type_terms ) {
echo \'<span>\'.$type_terms[0]->name .\'</span>\'; // All terms that exist in the \'state\' taxonomy are displayed.
}
?>
</li>
<?php endwhile; ?>
</ol>
<?php endif; ?>
<?php
}
}
wp_reset_postdata();
简单地说,我正在尝试这样的json:
{“store\\u type”:“xxx”,“state”:“ny”},{“store\\u type”:“yyy”,“state”:“ca”}
最合适的回答,由SO网友:FluffyKitten 整理而成
如果我正确理解您的要求,以下内容应该可以使用。
基本上,唯一的更改是在何处显示列表项,而不是回显列表项,而是将其保存到数组中。我们还知道此时的存储类型,因此可以将它们都保存在各自的数组中,作为主数组中的新元素。
$all_store_info = array(); // Declare array to save the store info
$post_type = \'store\';
$tax = \'store_type\';
$tax_terms = get_terms(\'store_type\');
if ( $tax_terms ) {
foreach ($tax_terms as $tax_term) {
$args = array([...]); // trimmed to make it easier to see changes
$my_query = new WP_Query($args);
if ( $my_query->have_posts() ) :
while ($my_query->have_posts()) : $my_query->the_post();
$type_terms = wp_get_post_terms( $post->ID, \'state\');
if ( $type_terms ) {
/* Add this store type from $tax_term from the outer loop
and the first (presumably only) state to our array */
$all_store_info[] = array(
"store_type" = $tax_term->name,
"state" = $type_terms[0]->name
);
}
endwhile;
endif;
}
}
wp_reset_postdata();