I have the following class:
class MultiArray
{
private $array = array();
public function add()
{
$keys = func_get_args();
$value = array_pop($keys);
$array =& $this->array;
foreach ($keys as $key) {
if (!isset($array[$key])) {
$array[$key] = array();
}
$array =& $array[$key];
}
if (!in_array($value, $array)) {
$array[] = $value;
}
}
public function getData()
{
return $this->array;
}
}
Here's an example on how to use it:
$words = new MultiArray();
$words->add('A');
$words->add('A', 'airplane');
$words->add('C', 'car', 'Nissan');
$words->add('R', 'road', '16th avenue', 'Richmond');
print_r($words);
This will output:
Array
(
[0] => A
[A] => Array
(
[0] => airplane
)
[C] => Array
(
[car] => Array
(
[0] => Nissan
)
)
[R] => Array
(
[road] => Array
(
[16th avenue] => Array
(
[0] => Richmond
)
)
)
)
It does the job but I feel like this is bad code. Is there a way to improve this code?