如何根据数组元素 属性 的值将数组重组为对象?

How to re-structure an Array to an Object based on the value the array elements' property?

我有这个数组,(其中包含 "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 or PHP Array function 将数组重新构造为对象:

{
    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"
    },
    ]
}

将 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);