Last active
November 17, 2015 14:13
-
-
Save helpse/200e49e9ea7b0ebc1c8d to your computer and use it in GitHub Desktop.
Get a tree from an array and indicators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Author: Sergio Melendez | |
* www.inspiredsolutions.pe | |
* | |
* Usage: | |
* $data = TreeArray::factory($array, $indicators)->get(); | |
* | |
* Input: [['a': 1, 'b': 2],['a': 1, 'b': 3]] | |
* Input: ['a'] | |
* Output: ['a': [['b': 2], [b: 3]]] | |
* | |
*/ | |
class TreeArray { | |
private $_data; | |
private $_indicadores; | |
public static function factory($data, $indicadores) | |
{ | |
return new TreeArray($data, $indicadores); | |
} | |
public function __construct($data, $indicadores) | |
{ | |
$this->_data = $data; | |
$this->_indicadores = $indicadores; | |
} | |
public function get() | |
{ | |
$data = $this->_data; | |
$indicadores = $this->_indicadores; | |
$result = array(); | |
foreach ($data as $row) | |
{ | |
$inner = &$result; | |
foreach ($indicadores as $indicador) | |
{ | |
$value = $row[$indicador]; | |
if ( ! isset($inner[$value])) | |
$inner[$value] = array(); | |
$inner = &$inner[$value]; | |
unset($row[$indicador]); | |
} | |
$inner = $row; | |
} | |
return $result; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment