Skip to content

Instantly share code, notes, and snippets.

@helpse
Last active November 17, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save helpse/200e49e9ea7b0ebc1c8d to your computer and use it in GitHub Desktop.
Save helpse/200e49e9ea7b0ebc1c8d to your computer and use it in GitHub Desktop.
Get a tree from an array and indicators
<?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