Syntax created dynamically

Asked

Viewed 69 times

1

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

It’s like this:

Given the values of a Matrix

Coluna 1  - Coluna 2

   190       340

   190       54

Where, the data in column 1. They are the parents of the data in column 2. At line zero the value (190) is being the father 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 alone according to my matrix, with the amount of values it has.

For the matrix can (and will) have more lines.

  • Your tree has only two levels, right? (i.e. you can’t 190 father of 340 and 340 father of 42. Or does it? ) In other words, the number that appears in the first column will always be in level 1, and the number that appears in the second will always be in level 2, is that right? P.S. By any chance your array is sorted? This would make it a lot easier...

1 answer

2


If your input matrix is sorted, this greatly facilitates the operation, as just save in a variable the last array created and check if the parent of the next line is the same. If it is, add column 2 in your children; if it is not, create a array new. 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 the ideone. P.S. I have little practical experience with PHP, so the above code may not be the best way to implement, but the logic I want to pass is this.

Browser other questions tagged

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