I am tidying up some old code i've come across on a job including various arrays which i'd like to combine into nested arrays and would like to know a simple way of looping throught the contents of a nested array (likely that there's a better way to store the data than a nested array in the first place, if so, suggestions welcome).
The following code is just an example of the original code structure, behaves in the same way just generalised output.
$someArray elements used to be defined indifvidually which seems very time consuming to manage hence why i want to change it:
$fruit['fruit']['apple']['size'] = 'small';
$fruit['fruit']['apple']['colour'] = 'red';
$fruit['fruit']['apple']['taste'] = 'bitter';
$fruit['fruit']['pear']['size'] = 'big';
$fruit['fruit']['pear']['colour'] = 'green';
$fruit['fruit']['pear']['taste'] = 'sweet';
Here's an example of the nested arrays that i'm building:
class someEntity
{
public function someFunction()
{
$someArray = array
(
'apple' => array(
'size' => 'small',
'colour' => 'red',
'taste' => 'bitter'
),
'pear' => array(
'size' => 'big',
'colour' => 'green',
'taste' => 'sweet'
)
);
return($someArray);
}
public function anotherFunction()
{
# some other stuff
}
}
Calling via foreach loop:
$someArray= someEntity::someFunction();
var_dump($someArray);
foreach($someArray as $key)
{
foreach($key as $key => $value)
{
print($key.': '.$value.'<br>');
}
}
array (size=2)
'apple' =>
array (size=3)
'size' => string 'small' (length=5)
'colour' => string 'red' (length=3)
'taste' => string 'bitter' (length=6)
'pear' =>
array (size=3)
'size' => string 'big' (length=3)
'colour' => string 'green' (length=5)
'taste' => string 'sweet' (length=5)
Output:
size: small colour: red taste: bitter size: big colour: green taste: sweet
Questions:
- What's the best way to compress the $fruits array? Is my $someArray approach incorrect?
- Is there a better way to call $someArray data without nested foreach loops?
Consider:
- The nested arrays may get more complex, possible an additional layer deep
- Do not want to use a database for this scenario
Thank you in advance
Updated
I've reworked as follows using an object.
class fruit
{
private $_type;
private $_size;
private $_colour;
private $_taste;
public function __construct($type,$size,$colour,$taste)
{
$this->_type = $type;
$this->_size = $size;
$this->_colour = $colour;
$this->_taste = $taste;
}
public function displayFruitData()
{
echo'<br>'.$this->_type.'<br>'.$this->_size.'<br>'.$this->_colour.'<br>'.$this->_taste.'<br><br>';
}
}
$fruit1 = new fruit("apple","small","red","bitter");
$fruit2 = new fruit("pear","medium","yellow","sweet");
$fruit3 = new fruit("pineapple","large","brown","sweet");
$output = $fruit1->displayFruitData();
$output = $fruit2->displayFruitData();
$output = $fruit3->displayFruitData();
exit();