2016-01-21 137 views
0

我在我的存儲庫中有一個自定義查詢,可以讓我接受郵政編碼或城市名稱作爲值。查詢結果的部分分組

這些值被提供給自動完成文本輸入。

public function findByZipOrCity($cz) 
{ 


    $qb = $this->createQueryBuilder('z'); 

    if (substr($cz, 0, 1) == "0") { 
     $cz = substr($cz, 1); 
     $qb 
      ->select('z') 
      ->where($qb->expr()->orX(
       $qb->expr()->like('z.city', ':czRequest'), 
       $qb->expr()->like('z.code', ':czRequest') 
      )) 
      ->andWhere('z.code <= :smaller') 
      ->setParameter('czRequest', $cz . '%') 
      ->setParameter('smaller', 9999); 
    } else { 
     $qb 
      ->select('z') 
      ->where($qb->expr()->orX(
       $qb->expr()->like('z.city', ':czRequest'), 
       $qb->expr()->like('z.code', ':czRequest') 
      )) 
      ->setParameter('czRequest', $cz . '%'); 
    } 


    return $qb->getQuery()->getArrayResult(); 
} 

我與此ArrayResult()到輸出JSON該自動提示plgin接受工作:

$zipcodes = $this->getDoctrine()->getManager()->getRepository("AppBundle:Zip")->findByZipOrCity($zip); 

    $response = new JsonResponse(); 
    $codes = array(); 

    foreach ($zipcodes as $zipcode) { 
     $codes[] = array(
      'id' => $zipcode['id'], 
      'country' => $zipcode['country'], 
      'city' => $zipcode['city'], 
      'code' => sprintf('%05d', $zipcode['code']), 
     ); 
    } 

    $response->setData($codes); 

    return $response; 

所以查詢關於 'berli' 給出以上的結果,自動提示看起來像這樣: Autosuggest

這工作正常,現在我想改變(任何)的功能,讓它像這樣顯示: Autosuggest Altered

我必須更改哪些功能?我可以對查詢進行分組嗎(我需要一個有效的zip),或者之後只對數組做「事情」?

任何提示高度讚賞!

+0

你試過分組? –

回答

0

您可以在陣列像如下改變:

foreach ($zipcodes as $zipcode) { 
     $codes[$zipcode['id']] = array(
      'id' => $zipcode['id'], 
      'country' => $zipcode['country'], 
      'city' => $zipcode['city'], 
      'code' => sprintf('%05d', $zipcode['code']), 
     ); 
    }