简体   繁体   中英

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

I have this array,(which contains all the definition of "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"
    },
]

Is it possible to re-structure the Array to an Object with Underscore-PHP or PHP Array function by grouping the array elements based on the value of < class_ > like that:

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

The algorithm to convert your json string into a grouped one would be like this:

  • Decode the json string using json_decode() function to get a multidimensional array.
  • Loop through the array to group the array elements as per your need.
  • Finally encode the array using json_encode() function to get the desired json string.

So your code should be like this:
(Suppose $json is your original json string)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM