이전 목록 다음

mysql data 가공에 대해 질문드립니다.

이곳에 질문하는게 맞는지 모르겠지만;;

 

 

Copy
[

  {id: 1, store: '우리동네 카페', drink: '아메리카노', price: 2500},

  {id: 1, store: '우리동네 카페', drink: '카페라떼', price: 3500},

  {id: 1, store: '우리동네 카페', drink: '수박주스', price: 4500},

  {id: 2, store: '이디야', drink: '아메리카노', price: 1500},

  {id: 2, store: '이디야', drink: '핫초코', price: 2500}

]

 

select join 문 사용하여 위와 같은 형태의 데이터를 받아왔다고 쳤을때

받아온 데이터를 아래의 형태로 가공하고자 하려면 어떻게 해야 하는지요...

 

Copy
[

  {

    id: 1,

    store: '우리동네 카페',

    storeInfo: [

      { drink: '아메리카노', price: 2500 },

      { drink: '카페라떼', price: 3500 },

      { drink: '수박주스', price: 4500 }

    ]

  },

  {

    id: 2,

    store: '이디야',

    storeInfo: [

      { drink: '아메리카노', price: 1500 },

      { drink: '핫초코', price: 2500 }

    ]

  }

]

 

감사합니다~

|

답변 1개

오류검사는 하지 않았습니다.

 

Copy
$result = mysqli_query(" select * from tbl");

while($row=mysqli_fetch_assoc($result)){

   if(!isset($data[$row['id']]['id']))
        $data[$row['id']]['id'] = $row['id'];

   if(!isset($data[$row['id']]['store']))
           $data[$row['id']]['store'] = $row['store'];

   $storeInfo['drink'] = $row['drink'];
   $storeInfo['price'] = $row['price'];
   
   $data[$row['id']]['storeInfo'][] = $storeInfo;    
}

foreach($data as $id=>$array )
    $return[] = $array;

var_dump($return);

답변을 작성하려면 로그인이 필요합니다.