2016-09-24 4 views
1

PHP는 json 다중 배열을 만듭니다. PHP와 코드를 다음과 같은 출력을 필요로 그 json .. 너무 많은 배열과 개체 나를 혼란. 우리가 사용 wordpresPHP는 json 다중 배열을 만듭니다

<?php 
$categories = get_categories(array(
    'orderby' => 'name', 
    'parent' => 0 
)); 

foreach ($categories as $category) { 
    $category_id = $category->term_id; 
    $category_name = $category->name; 
    echo $category_name; 
    echo "<br>"; 

     $args = array(
      'post_type' => 'post', 
      'post_status' => 'publish', 
      'category' => $category_id 
     ); 

     $myposts = get_posts($args); 
     foreach($myposts as $post){ 
      $category_postname = $post->post_title; 
      echo $category_postname; 
      echo "<br>"; 
     } 
} 
?> 

빌 출력은

Testcat1 
     pos1 
     post2 
    Testcat2 
     post3 
     post4 
    TestCat3 
     post5 
     post 6 

는이 같은 JSON을 만들 필요가있다 "이다. 내가이 JSON 출력처럼 필요

{ 
     "data": [ 
     { 
      "cat": "Testcat1", 
      "post": [ 
      { 
       "name": "post1" 
      }, 
      { 
       "name": "post2" 
      } 
      ] 
     }, 
     { 
      "cat": "Testcat2", 
      "post": [ 
      { 
       "name": "post3" 
      }, 
      { 
       "name": "post4" 
      } 
      ] 
     }, 
     { 
      "cat": "Testcat3", 
      "post": [ 
      { 
       "name": "post5" 
      }, 
      { 
       "name": "post6" 
      } 
      ] 
     } 
     ] 
    } 

+0

json_encode는 어떻습니까? – Jeff

답변

0

당신은 모든 것을 놓아야합니다 배열과 json_encode it. 나는 여러분의 echo를 주석 처리 했으므로 나중에 필요할 경우 사용할 수 있습니다.

<?php 
$categories = get_categories(array(
    'orderby' => 'name', 
    'parent' => 0 
)); 

// init empty array with root "data" 
$array = array('data' => array()); 
// set counter to 0 for array later on 
$n = 0; 

foreach ($categories as $category) { 
    $category_id = $category->term_id; 
    $category_name = $category->name; 

    // store cat.name 
    $array['data'][$n]['cat'] = $category_name; 
    // echo $category_name; 
    // echo "<br>"; 

    $args = array(
     'post_type' => 'post', 
     'post_status' => 'publish', 
     'category' => $category_id 
    ); 

    $myposts = get_posts($args); 
    // init posts counter 
    $i = 0; 
    foreach($myposts as $post){ 
     $category_postname = $post->post_title; 
     $array['data'][$n]['post'][$i]['name'] = $category_postname; 
     $array['data'][$n]['post'][$i]['id'] = $post->ID; 
     // echo $category_postname; 
     // echo "<br>"; 
     // increment post loop counter 
     $i++; 
    } 

    // increment counter for array 
    $n++; 
} 

echo json_encode($array); 
?> 
+0

네, 잘 작동 해 주셔서 감사합니다. – suresh

+0

@suresh 아무런 문제가 없습니다. 당신은이 대답을 당신이 사용하게 될 방법으로 선택할 수 있습니다. – Omnisite

+0

어떻게 포스트 배열에 $ category_postid를 추가 할 수 있습니까 ?? "post": [ { "name": "post5", "id": "1", } – suresh

관련 문제