我有这个数组,(其中包含" love" btw的所有定义):
[
{
def: "a strong positive emotion of regard and affection",
exemple: "hildren need a lot of love",
class_: "noun"
},
{
def: "any object of warm affection or devotion",
exemple: "the theater was her first love",
class_: "noun"
},
{
def: "sexual activities (often including sexual intercourse) between two people",
exemple: "he has a very complicated love life",
class_: "noun"
},
{
def: "have a great affection or liking for",
exemple: "She loves her boss and works hard for him",
class_: "verb"
},
{
def: "get pleasure from",
exemple: "I love cooking",
class_: "verb"
},
]
是否可以通过基于<的数值对数组元素进行分组,将数组重新构造为具有Underscore-PHP或PHP Array function的对象。 class_>那样:
{
noun: [
{
def: "a strong positive emotion of regard and affection",
exemple: "hildren need a lot of love",
class_: "noun"
},
{
def: "any object of warm affection or devotion",
exemple: "the theater was her first love",
class_: "noun"
},
{
def: "sexual activities (often including sexual intercourse) between two people",
exemple: "he has a very complicated love life",
class_: "noun"
},
],
verb: [
{
def: "have a great affection or liking for",
exemple: "She loves her boss and works hard for him",
class_: "verb"
},
{
def: "get pleasure from",
exemple: "I love cooking",
class_: "verb"
},
]
}
答案 0 :(得分:1)
将json字符串转换为分组字符串的算法如下:
json_decode()
函数解码json字符串以获取多维数组。json_encode()
函数对数组进行编码,以获得所需的json字符串。所以你的代码应该是这样的:
(假设$json
是您原来的json字符串)
// suppose $json is your original json string
$array = json_decode($json, true);
$resultArr = array();
foreach($array as $arr){
$resultArr[$arr['class_']][] = $arr;
}
// display the resultant json string
echo json_encode($resultArr);