I'm creating a checkout for customers and the data about what's in their cart is being sent to a page (for just now) via $_GET.
I want to extract that data and then populate a multidimensional array with it using a loop.
Here's how I'm naming the data:
$itemCount = $_GET['itemCount'];
$i = 1;
while ($i <= $itemCount) {
${'item_name_'.$i} = $_GET["item_name_{$i}"];
${'item_quantity_'.$i} = $_GET["item_quantity_{$i}"];
${'item_price_'.$i} = $_GET["item_price_{$i}"];
//echo "<br />Name: " .${'item_name_'.$i}. " - Quantity: " .${'item_quantity_'.$i}. " - Price: ".${'item_price_'.$i};
$i++;
}
From here I'd like to create a multidimensional array like such:
Array
(
[Item_1] => Array
(
[item_name] => Shoe
[item_quantity] => 2
[item_price] => 40.00
)
[Item_2] => Array
(
[item_name] => Bag
[item_quantity] => 1
[item_price] => 60.00
)
[Item_3] => Array
(
[item_name] => Parrot
[item_quantity] => 4
[item_price] => 90.00
)
.
.
.
)
What I'd like to know is if there is a way I can create this array in the existing while
loop? I'm aware of being able to add data to an array like $data = []
after delacring an empty array but the actual syntax eludes me.
Maybe I'm completely off the right track and there is a better way of doing it?
Thanks
Try something like this...
$itemCount = $_GET['itemCount'];
$i = 1;
$items = array();
while ($i <= $itemCount) {
$items['Item_'.$i]['item_name'] = $_GET["item_name_{$i}"];
$items['Item_'.$i]['item_quantity'] = $_GET["item_quantity_{$i}"];
$items['Item_'.$i]['item_price'] = $_GET["item_price_{$i}"];
$i++;
}
$result = array();
$itemCount = $_GET['itemCount'];
$i = 1;
while ($i <= $itemCount) {
$tmp = array();
$tmp['item_name'] = $_GET["item_name_{$i}"];
$tmp['item_quantity'] = $_GET["item_quantity_{$i}"];
$tmp['item_price'] = $_GET["item_price_{$i}"];
//echo "<br />Name: " .${'item_name_'.$i}. " - Quantity: " .${'item_quantity_'.$i}. " - Price: ".${'item_price_'.$i};
$i++;
$result['Item_{$i}'] = $tmp;
}
$itemCount = $_GET['itemCount'];
$i = 1;
my_array = [];
while ($i <= $itemCount) {
${'item_name_'.$i} = $_GET["item_name_{$i}"];
${'item_quantity_'.$i} = $_GET["item_quantity_{$i}"];
${'item_price_'.$i} = $_GET["item_price_{$i}"];
//echo "<br />Name: " .${'item_name_'.$i}. " - Quantity: " .${'item_quantity_'.$i}. " - Price: ".${'item_price_'.$i};
my_array["Item_".$i] = array(
"item_name"=>$_GET["item_name_{$i}"],
"item_quantity"=>$_GET["item_quantity_{$i}"],
"item_price"=>$_GET["item_price_{$i}"]
);
$i++;
}
var_dump(my_array);
$arr = array();
for($i = 1; isset(${'item_name_'.$i}); $i++){
$arr['Item_'.$i] = array(
'item_name' => ${'item_name_'.$i},
'item_quantity' => ${'item_quantity_'.$i},
'item_price' => ${'item_price_'.$i},
);
}