I am trying to implement multidimensional array that hold data of Pizza id’s with options and extras id’s.
Let look at the following scenario…
Customer wants
-
Two ‘Chicken Pizza’ (
ProductID:12) – ’10 inches’ (OptionsID:4) with extras of Ham and Tuna (ExtrasID: 5,10) -
One ‘Chicken Pizza’ (
ProductID:12) – ’10 inches’ (OptionsID:4) with extras of Sweet Corn (ExtrasID: 2) -
One ‘Chicken Pizza’ (
ProductID:12) – ’14 inches’ (OptionsID:2) with no extras -
Eleven ‘Vegetarian Pizza’ (
ProductID:35) – ‘7 inches’ (OptionsID:52) with no extras
See the following code below that match the scenario… Im I doing it right? or what can be done to improve it and readable?
//Two 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4)
//With extras of Ham and Tuna (ExtrasID: 5,10)
$option4[] = array(
'quantity' => 2,
'extras_id' => array(5, 10)
);
//One 'Chicken Pizza' (ProductID:12) - '10 inches' (OptionsID:4)
//With extras of Sweet Corn (ExtrasID: 2)
$option4[] = array(
'quantity' => 1,
'extras_id' => array(2)
);
//One 'Chicken Pizza' (ProductID:12) - '14 inches' (OptionsID:2)
//With no extras
$option2[] = array(
'quantity' => 1,
'extras_id' => array()
);
//Eleven 'Vegetarian Pizza' (ProductID:35) - '7 inches' (OptionsID:52)
//With no extras
$option52[] = array(
'quantity' => 11,
'extras_id' => array()
);
//Hold data of Customer Orders
$shoppingBasket = array(
"ShopID_24" => array(
'ProductID' => array(
'12' => array(
'OptionID' => array(
'4' => $option4,
'2' => $option2
)
),
'35' => array(
'OptionID' => array(
'52' => $option52
)
),
)
)
);
echo "<pre>";
print_r($shoppingBasket);
echo "</pre>";
print_r output:
Array
(
[ShopID_24] => Array
(
[ProductID] => Array
(
[12] => Array
(
[OptionID] => Array
(
[4] => Array
(
[0] => Array
(
[quantity] => 2
[extras_id] => Array
(
[0] => 5
[1] => 10
)
)
[1] => Array
(
[quantity] => 1
[extras_id] => Array
(
[0] => 2
)
)
)
[2] => Array
(
[0] => Array
(
[quantity] => 1
[extras_id] => Array ()
)
)
)
)
[35] => Array
(
[OptionID] => Array
(
[52] => Array
(
[0] => Array
(
[quantity] => 11
[extras_id] => Array ()
)
)
)
)
)
)
)
I would consider doing this by modeling the same data in a few custom PHP objects. In this case you might have a shop object with products, and product objects with options. This is really quick off the top of my head:
What does this get you? For starters, you can define limits and parameters to what you can store in this, while with the nested array that you are using, there is absolutely no enforcement of structure or value. You can also define other methods that allow you to actually DO things with these bits of data.
If you absolutely MUST have an array version of these, you can implement something like a
toArray()method in each of these that will convert the objects into an array to be consumed by some other bit of code. You might also consider reading up on a few interfaces such as iterator and countable in the PHP manual.