Json按照首字母分组

时间:2015-03-04 01:41:59

标签: php json symfony

我在存储库中使用这些行来获取名称列表:

$qb = $this->createQueryBuilder('p')
->select('p.number', 'p.name', 'p.nationality', 'SUBSTRING(p.name, 1, 1) initial')
->orderBy('p.name', 'ASC');
$result = $qb->getQuery()->getArrayResult();

print_r($result)
Array (
       [0] => Array ( [number] => 253 [name] => Athena [nationality] => Japan [initial] => A ) 
       [1] => Array ( [number] => 42 [name] => Kyo [nationality] => Japan [initial] => K ) 
       [2] => Array ( [number] => 3 [name] => Kensou [nationality] => Japan [initial] => K ) 
       [3] => Array ( [number] => 68 [name] => Clark [nationality] => USA [initial] => C ) 
       [4] => Array ( [number] => 58 [name] => Ralph [nationality] => USA [initial] => R ) 
       [5] => Array ( [number] => 23 [name] => Ryo [nationality] => Spain [initial] => R ) )

我得到了这个结果:

{"players":[
   {"number":"253", "name":"Athena","nationality":"Japan","initial":"A},
   {"number":"42", "name":"Kyo","nationality":"Japan","initial":"K"},
   {"number":"3", "name":"Kensou","nationality":"Japan","initial":"K"},
   {"number":"68", "name":"Clark","nationality":"USA","initial":"C"},
   {"number":"85", "name":"Ralph","nationality":"USA","initial":"R"},
   {"number":"23", "name":"Ryo","nationality":"SPAIN","initial":"R"},
]}

我怎么能有类似的东西:

{"players":[
    {"A":[
        {"name":"Athena", number: "253", nationality: "Japan"}
    ]},
   {"K":[
        {"name":"Kyo", number: "42", nationality: "Japan"},
        {"name":"Kensou", number: "3", nationality: "Japan"}
    ]},
    {"C":[
        {"name":"Clark", number: "68", nationality: "USA"}
    ]},
    {"R":[
        {"name":"Ralph", number: "85", nationality: "USA"},
        {"name":"Ryo", number: "23", nationality: "Spain"}
    ]},
]}

我不知道是否可能有类似的结果。我需要找到一个解决方案来获取这个名字列表,这些名字按照json中的initial分组。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

我用这句话解决了这个问题:

$playersByInitial = array();
foreach($players as $player){
    $playersByInitial[$player["initial"]][] = array(
        "name" => $player["name"],
        "number" => $player["number"], 
        "nationality" => $player["nationality"]
     );
}