重写JSON字符串 - 按值将键分组为新的两级深度数组?

时间:2012-12-23 02:47:31

标签: php arrays json

在此基础上构建我之前的问题:

Rewriting a JSON string - grouping keys by value into a new array?

我想知道如何遍历给定的数组并使用它,以便输出出现如下:

[{
"Name": "Title 1",
"Date": "2012-12-05",
"rows": [
    {
        "Subtitle": "Subtitle 1",
        "Count1": 566,
        "Count2": 105
    },
    {
        "Subtitle": "Subtitle 2",
        "Count1": 76,
        "Count2": 15
    }
    ]
}, 
{
"Name": "Title 2",
"Date": "2012-12-06",
"rows": [
    {
        "Count1": 66,
        "Count2": 5
    }...

其中原始json数组按“Name”列分组,然后分类为这样的多级结构(父/多子json结构,以便在我们的应用程序中正确构建菜单)?

原始的json数据如下所示:

[{
"Name": "Title 1",
"Subtitle": "Subtitle 1",
"Count1": 556,
"Count2": 5,
"Date": "2012-12-05"
}, {
"Name": "Title 1",
"Subtitle": "Subtitle 2",
"Count1": 10,
"Count2": 100,
"Date": "2012-12-05"
}, {
"Name": "Title 3",
"Subtitle": "Subtitle 3",
"Count1": 798,
"Count2": 11,
"Date": "2012-12-04"
}...

显然我正在寻找PHP的解决方案,因为我将在json数据中读取,处理它并将其重新格式化。

2 个答案:

答案 0 :(得分:2)

假设关联数组和按名称排序输出:

$output = array();

for ($data as $row) {

    if (!isset($output[$row['Name']])) {
        $output[$row['Name']] = array(
            'Name' => $row['Name'],
            'Date' => $row['Date'],
            'rows' => array()
        );
    }

    $output[$row['Name']]['rows'][] = array(
        'Subtitle' => $row['Subtitle'],
        'Count 1'  => $row['Count 1'],
        'Count 2'  => $row['Count 2'] 
    );
}

答案 1 :(得分:1)

hash = {};
result = [];
for (var i = 0; i < data.length; i++) {
    var name = data[i].Name;
    if (!hash.hasOwnProperty(name)) {
        var newitem = { Name: name,
                        Date: data[i].Date,
                        rows: []
                      };
        result.push(newitem);
        hash[name] = newitem;
    }
    hash[name].rows.push({ Subtitle: data[i].Subtitle,
                           Count1: data[i].Count1,
                           Count2: data[i].Count2
                         });
}