如何根据数组元素的值重新构造一个数组到一个对象'属性?

时间:2017-07-09 18:32:01

标签: php arrays underscore.js helper helpers

我有这个数组,(其中包含" 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-PHPPHP 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"
    },
    ]
}

1 个答案:

答案 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);