Syntax created dynamically

1

I have a syntax (in php) to generate the Json file. But I need this syntax to be created dynamically, that is, according to the result of another class.

You're like this:

Given the values of a Matrix

Coluna 1  - Coluna 2

   190       340

   190       54

Given that, the data in column 1 are the parents of the data in column 2. At line zero the value (190) is being the parent of the value (340), and so on.

Given these values, the syntax would look like this:

$name = "name";
$children = "children";
$valor1 = "190";
$valor2 = "340";
$var = array ($name=>"$valor1",$children=>array(array($name=>"$valor2"),array($name=>"$ip1")));
$ip = json_encode($var, JSON_PRETTY_PRINT);

I need the syntax, which is entering the variable $ var. Be created by myself according to my matrix, with the amount of values it has.

Because the array can (and will) have more rows.

    
asked by anonymous 26.11.2014 / 12:57

1 answer

2

If your input array is ordered, this makes the operation quite easy, since you just have to store the last% created_co_de% in a variable and check if the parent of the next line is equal. If so, add column 2 to your children; if it is not, it creates a new array . Example:

$entrada = array(
    array(col_1=>190, col_2=>340),
    array(col_1=>190, col_2=>54),
    ...
);

$name = "name";
$children = "children";
$var = array(); # $var será um array (top level) cujos elementos são o pai e seus filhos
                # Se você quer algo diferente como a raiz da sua árvore, é necessário definir
                # o que.

asort($entrada); # Ordenar de modo que os valores da coluna 1 venham juntos

$ultimo = null;
foreach($entrada as $colunas) {
    # Cria um array novo se o último tiver um pai diferente
    if ( is_null($ultimo) || $ultimo[$name] != $colunas["col_1"] ) {
        if ( !is_null($ultimo) )
            array_push($var, $ultimo);
        $ultimo = array($name=>$colunas["col_1"], $children=>array());
    }
    # Adiciona o filho no pai
    $ultimo[$children][] = array($name => $colunas["col_2"]);
}
if ( !is_null($ultimo) )
    $var[] = $ultimo;

$ip = json_encode($var, JSON_PRETTY_PRINT);

Example in ideone . Q. I have little practical experience with PHP, so the above code may not be the best way to implement it, but the logic I want to pass on is this.

    
26.11.2014 / 15:19