PHP - Array - Horizontal Keys

Asked

Viewed 118 times

4

Situation

I own 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

Wish to leave it so :

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

I mean, my key order tree is the order of the keys of the array.

Someone knows how to implement this?

  • Related, but you will need to do this for each level of your structure.

  • And how do you intend to maintain the values? Aiming that now everything will be nestled and arrays.

  • @Patrickmaciel, values are not important can be lost, serve only as an ordination helper. Ex.: a chave that has as value = null is the father of all, the chave = 1 is the daughter of the former and so on.

1 answer

2


Good to solve my problem I set up this function, it’s been a while since I just posted it.
She works with the idea I want, but is limited to array monodimentional, that is if anyone else wants to use it.

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
                        (
                        )

                )

        )

)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.