代码之家  ›  专栏  ›  技术社区  ›  Monero Jeanniton

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

  •  0
  • Monero Jeanniton  · 技术社区  · 7 年前

    我有一个数组(包含了“爱”的所有定义):

    [
        {
            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

    {
        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"
        },
        ]
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Rajdeep Paul    7 年前

    将json字符串转换为 分组 一个是这样的:

    • json_decode() 函数获取多维数组。
    • 循环遍历数组,根据需要对数组元素进行分组。
    • 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);