如何在php中为具有类似值的数组分组JSON输出

时间:2016-11-02 03:57:20

标签: php arrays json wordpress

我正在使用WordPress数据创建一个数组:

  // get list of tags
    $custom_terms = get_terms('post_tag');
    $term_all = array();
    $cats_all = array();

   foreach($custom_terms as $custom_term) {
       wp_reset_query();
       $args = array('post_type' => 'post',
           'tax_query' => array(
               array(
                   'taxonomy' => 'post_tag',
                   'field' => 'slug',
                   'terms' => $custom_term->slug,
               ),
           ),
        );

        $loop = new WP_Query($args);
        if($loop->have_posts()) {
           while($loop->have_posts()) : $loop->the_post();
           $categories = get_the_category();

           // create the array
           $cats_all[] = array(
             'term_name'=>$custom_term->name,
             'category_details'=>array(
             'category_ID'=> $categories[0]->term_id,
             'category_name' => $categories[0]->name,
             ),
           );
           endwhile;
        }
   }

当输出杰森时,我得到了这个结果:

{
  "status": "ok",
  "all_tags": [
    {
      "term_name": "Tag 1",
      "category_details": {
        "category_ID": 7,
        "category_name": "category 3"
      }
    },
    {
      "term_name": "Tag 1",
      "category_details": {
        "category_ID": 6,
        "category_name": "category 2"
      }
    },
    {
      "term_name": "Tag 1",
      "category_details": {
        "category_ID": 5,
        "category_name": "category 1"
      }
    },
    {
      "term_name": "Tag 2",
      "category_details": {
        "category_ID": 8,
        "category_name": "category 4"
      }
    }
  ]
}

但正如您所看到的,标签1有许多类别,因此我希望所有类别都在一个标签名称下。像这样:

{
  "status": "ok",
  "all_tags": [
    {
      "term_name": "Tag 1",
      "category_details": [
        {
          "category_ID": 7,
          "category_name": "category 3"
        },
        {
          "category_ID": 6,
          "category_name": "category 2"
        },
        {
          "category_ID": 5,
          "category_name": "category 1"
        }
      ],
    },
    {
      "term_name": "Tag 2",
      "category_details": [
        {
          "category_ID": 8,
          "category_name": "category 4"
        },
      ]
    }
  ]
}

我似乎找不到像这样显示数据的方法。有人可以解释一下如何得到这个结果吗?

1 个答案:

答案 0 :(得分:0)

您可以使用密钥索引标签重新编码您的代码段,如下标记

$("button.btn-transcript").on('click', 'button.btn-transcript', function(event, el)) {
  transTarget = $(this).readAttribute("data-target");
  function(event,el) {
    if($(this).hasClassName("collapsed")) {
      $("transTarget").show();
      $(this).removeClassName("collapsed");
      $(this).writeAttribute("area-expanded", "true");
    } else {
      $("transTarget").hide();
      $(this).addClassName("collapsed");
      $(this).writeAttribute("area-expanded", "false");
    }
  }