PHP - Array - Vertical Keys for Horizontal

4

Situation

I have an array as follows:

Array
(
    [1] => Array
        (
            [tree] => Array
                (
                    [tb_agenda_hora] => 2,
                    [tb_agenda_fase] => 1,
                    [tb_agenda] => null
                )
        )

    [2] => Array
        (
            [tree] => Array
                (
                    [tb_prospeccao] => 1,
                    [tb_agenda] => null
                )
        )
)

Need

Do you want to leave it like this:

Array
(
    [tb_agenda] => Array(
        [tb_agenda_fase] => Array(
            [tb_agenda_hora] => Array()
        ),
        [tb_prospeccao] => Array()
    )
)

That is, my order of the key tree is the order of the keys of array .

Does anyone know how to implement this?

    
asked by anonymous 12.06.2015 / 21:35

1 answer

2

Good to solve my problem I mounted this function, it's been a while since I just did not post it. It works with the idea that I want, but it is limited to only array monodimencional, that is if someone else wants to use it, it will have to adapt.

function addArrayH(&$array, $value){
    if(is_array($array) && !empty($array)){
        foreach ($array as $k => $dados){
            if(is_array($dados) && !empty($dados)){
                addArrayH($array[$k], $value);
            }else{
                $array[$k] = $value;
            }
        }
    }else{
        $array = $value;
    }
}

# MONTA ARVORE DA SEQUENCIA
$tmp = array();
foreach($array as $k => $options){
    foreach (array_reverse($options['tree']) as $tableOrder => $fkOrder){
        $order = array($tableOrder => array());
        $this->addArrayH($tmp, $order);
    }
}

More Example

$temp = array(
    'teste1' => array(
        'teste1.1' => array(
            'teste1.1.1'
        ),
    ),
    'teste2' => array(
        'teste2.1' => array(
            'teste1.2.1'
        ),
        'teste2.2' => array(
            'teste1.2.1'
        ),
    ),
    'teste3' => null,

);

$tmp = array();
foreach ($temp as $k => $value){
    $order = array($k => array());
    $this->addArrayH($tmp, $order);
}

Out

Array
(
    [teste1] => Array
        (
            [teste2] => Array
                (
                    [teste3] => Array
                        (
                        )

                )

        )

)
    
25.06.2015 / 14:33