簡體   English   中英

如何根據數組元素的屬性值將數組重組為對象?

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

是否可以通過根據<class_>的值對數組元素進行分組,使用Underscore-PHPPHP Array函數將數組重新構造為對象,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM