Home > other >  PHP merge array by "depth"?
PHP merge array by "depth"?

Time:11-20

I have an array like this:

[
    {
        "function_1": {
            "element": {
                "error": "0",
                "msg": "test"
            }
        }
    },
    {
        "function_1": {
            "element_2": {
                "error": "0",
                "msg": "test"
            }
        }
    },
    {
        "function_2": {
            "element": {
                "error": "0",
                "msg": "test"
            }
        }
    },
    {
        "function_2": {
            "element_2": {
                "error": "0",
                "msg": "test"
            }
        }
    }
]

I want output like this:

[
    {
        "function_1": {
            "element": {
                "error": "0",
                "msg": "test"
            },
            "element_2": {
                "error": "0",
                "msg": "test"
            }
        }
    },
    {
        "function_2": {
            "element": {
                "error": "0",
                "msg": "test"
            },
            "element_2": {
                "error": "0",
                "msg": "test"
            }
        }
    }
]

The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way. Thank you!

CodePudding user response:

Your data structure looks weird for the purpose you are trying to achieve I'm bored af tho and created this code for you

function combineElementsPerfunction($functions) {

   $result = [];

    $uniqueFunctions = [];
    foreach ($functions as $function) {
        $functionName = array_keys($function)[0];
        $uniqueFunctions[] = $functionName;
    }
    $uniqueFunctions = array_unique($uniqueFunctions);
    foreach ($uniqueFunctions as $uniqueFunction) {
        $functionObjects = array_filter(
            $functions,
            function($function) use ($uniqueFunction) {
                $functionName = array_keys($function)[0];
                return $functionName === $uniqueFunction;
            }
        );
        
        $elements = [];
        foreach ($functionObjects as $functionObject) {
            $function = array_shift($functionObject);
            $elements = array_merge($elements, $function);
        }
        
        $result[] = [
            $uniqueFunction => $elements
        ];
    }
    return $result;
}

CodePudding user response:

function changeArr($data){
    $box = $new = [];
    foreach ($data as $v){
        $key = array_key_first($v);
        $i = count($box);
        if(in_array($key, $box)){
            $keys = array_flip($box);
            $i = $keys[$key];
        }else{
            $box[] = $key;
        }
        $new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
    }
    return $new;
}
  • Related