递归合并类似索引 [英] Recursively merge like indexes

查看:44
本文介绍了递归合并类似索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,该数组具有我要合并在一起的相似索引.出于某种原因,我无法将头缠住它.

I have an array that has like indexes that I am trying to merge together. For some reason I can't wrap my head around it.

$seperateArray = json_decode('[
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Harold" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Arthur" },
{ "tier1": "Group1", "tier2": "Blue", "tier3": "Round", "tier4": "Tom" },
{ "tier1": "Group2", "tier2": "Blue", "tier3": "Round", "tier4": "Beth" },
{ "tier1": "Group3", "tier2": "Blue", "tier3": "Round", "tier4": "Peter" }]', true);

将其转换为:

{
    "Group1": {
        "Blue": {
            "Round": [
                "Harold",
                "Arthur",
                "Tom"
            ]
        }
    },
    "Group2": {
        "Blue": {
            "Round": [
                "Peter"
            ]
        }
    }
}

这是我目前所处的位置,但是我不知道我是否朝着正确的方向前进.

This is where I am at so far but I don't know if I'm moving in the right direction.

$newCombined = array();

//this each statement will show every tier 1-4 array object
foreach($seperateArray as $s) {

    if(!array_key_exists($s['tier1'], $newCombined) $newCombined[$s['tier1']] = array();
    if(!array_key_exists($newCombined[$s['tier1']][$s['tier2']], $newCombined[$s['tier1']])) $newCombined[$s['tier1']][$s['tier2']] = array();
    //.. and so on

}

推荐答案

如果只有 tier4 可以产生一个数组,那么循环和分配就很简单了(如果您可以使用静音的话)通知):

If only tier4 can produce an array, then it is a simple matter of looping and assigning (if you're ok with silencing notices):

$array = json_decode('...', true);
$new = [];

foreach ($array as $e)
    @$new[$e['tier1']][$e['tier2']][$e['tier3']][] = $e['tier4'];

echo json_encode($new, JSON_PRETTY_PRINT); # to print what you asked for

要使分配的内容更加隐秘:

To make the assignment a little less cryptic:

foreach ($array as $e) {
    list($t1, $t2, $t3, $t4) = array_values($e);
    @$new[$t1][$t2][$t3][] = $t4;
}


要从 $ new 返回原始数组:

$original = [];

foreach (array_keys($new) as $t1)
    foreach (array_keys($new[$t1]) as $t2)
        foreach (array_keys($new[$t1][$t2]) as $t3)
            foreach ($new[$t1][$t2][$t3] as $t4)
                $original[] = [
                    'tier1' => $t1,
                    'tier2' => $t2,
                    'tier3' => $t3,
                    'tier4' => $t4,
                ];

echo json_encode($original, JSON_PRETTY_PRINT);

这篇关于递归合并类似索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆