Pulling $_GET data and creating multidimensional array using loop - php

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},
);
}

Related

How to merge 3 arrays keeping their meta key?

I'm Getting some arrays from some wordpress custom fields:
$content = array(get_post_meta($postId, 'content'));
$media = array(get_post_meta($postId, 'media'));
$yt = array(get_post_meta($postId, 'youtube'));
I then need to have it printing in sequence, like:
media
content
LInk
Embed
And repeat the sequence for each value
media
content
LInk
Embed
For the sequence I'd use this:
echo '<ul>';
for ($i = 0; $i < count($all_array['media']); $i++) {
for ($j = 0; $j < count($all_array['content']); $j++) {
for ($k = 0; $k < count($all_array['youtube']); $k++) {
echo '<li>media->' . $all_array['media'][$i] . '</li>';
echo '<li>content->' . $all_array['content'][$j] . '</li>';
echo '<li>link->' . $all_array['link'][$k] . '</li>';
}
}
}
echo '</ul>';
But I'm doing something wrong with the merging of the 3 fields as if I do a var_dump before to run the for bit, like
echo '<pre>' . var_export($all_array, true) . '</pre>';
Then this is what I get and I cannot iterate as I wish:
array (
0 =>
array (
0 =>
array (
0 => '
brother
',
1 => '
Lorem
',
2 => '
End it
',
),
1 =>
array (
0 => '337',
1 => '339',
),
2 =>
array (
0 => 'https://www.youtube.com/watch?v=94q6fzbJUfg',
),
),
)
Literally the layout in html that I'm looking for is:
image
content
link
image
content
link
...
UPDATE
This how I am merging the arrays:
foreach ( $content as $idx => $val ) {
$all_array[] = [ $val, $media[$idx], $yt[$idx] ];
}
This is the associative array how it looks like:
Content:
array (
0 =>
array (
0 => '
brother
',
1 => '
Lorem
',
2 => '
End it
',
),
)
Media
array (
0 =>
array (
0 => '337',
1 => '339',
),
)
Youtube
array (
0 =>
array (
0 => 'https://www.youtube.com/watch?v=94q6fzbJUfg',
),
)
The way I've resolved it is first I calculate the tot. items within each array, then I get the array with max items and loop and add the items in sequence:
//GET CUSTOM FIELDS
$content = get_post_meta($post_to_edit->ID, 'content', false);
$media = get_post_meta($post_to_edit->ID, 'media', false);
$yt = get_post_meta($post_to_edit->ID, 'youtube', false);
$max = max(count($content), count($media), count($yt));
$combined = [];
//
// CREATE CUSTOM FIELDS UNIQUE ARRAY
for($i = 0; $i <= $max; $i++) {
if(isset($media[$i])) {
$combined[] = ["type" => "media", "value" => $media[$i]];
}
if(isset($content[$i])) {
$combined[] = ["type" => "content", "value" => $content[$i]];
}
if(isset($yt[$i])) {
$combined[] = ["type" => "youtube", "value" => $yt[$i]];
}
}
Finally I can loop:
foreach ($combined as $key => $val) {
if($val['type'] === "media") {
...
}
if($val['type'] === "content") {
...
You don't need to merge the arrays together. It will work fine in separate arrays. However, your for loops don't have the right logic. Try:
for ($i = 0; $i < count($media); $i++) {
for ($j = 0; $j < count($media[$i]); $j++) {
echo '<li>media->' . $media[$i][$j] . '</li>';
}
for ($j = 0; $j < count($content[$i]); $j++) {
echo '<li>content->' . $content[$i][$j] . '</li>';
}
for ($j = 0; $j < count($youtube[$i]); $j++) {
echo '<li>link->' . $youtube[$i][$j] . '</li>';
}
}

Building an associative array using for loop in php

I am trying to create an associative array using php. My desired output is
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
The code is
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr .= "array('key' => 'fl_".$i."_sq'),";
}
print_r($flr_arr);
Output is
array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),
Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.
You could do this:
<?php
$flr_arr = [];
$max_val = 2;
for ($i = 0; $i < $max_val; $i++) {
$flr_arr[][key] = 'fl_' . $i . '_sq';
}
$output = "<pre>";
foreach ($flr_arr as $i => $flr_arr_item) {
$output .= print_r($flr_arr_item, true);
if($i < count($flr_arr)-1){
$output = substr($output, 0, -1) . ",\n";
}
}
$output .= "</pre>";
echo $output;
The output:
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
I'm not exactly sure what you want to do, but your output could be done by this:
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr = [];
$flr_arr['key'] = 'fl_".$i."_sq';
print_r($flr_arr);
}
You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:
$flr_arr[] = array("key"=>"fl_$i_sq");
Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -
array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))

How to get specific array value in php

I want to output a specific value from array in php
Below is my code and array is $content
<?php
$content = $_POST;
for($i=1; $i < $content['itemCount'] + 1; $i++) {
$name = 'item_name_'.$i;
$quantity = 'item_quantity_'.$i;
$price = 'item_price_'.$i;
$image='item_image_'.$i;
$option='item_options_'.$i;
$total = $content[$quantity]*$content[$price];
}
?>
<?php
print_r( $content );
?>
Output is showing as below:
Array ( [currency] => INR
[shipping] => 0
[tax] => 0
[taxRate] => 0
[itemCount] => 3
[item_name_1] => Our Nest
[item_quantity_1] => 1
[item_price_1] => 1900
[item_options_1] => image: CF01108.jpg, productcode: 602793420
[item_name_2] => Our Nest
[item_quantity_2] => 1
[item_price_2] => 2100
[item_options_2] => image: CF01110.jpg, productcode: 123870196
[item_name_3] => Our Nest
[item_quantity_3] => 1
[item_price_3] => 1800
[item_options_3] => image: CF01106.jpg, productcode: 416267436 )
How to get productcode value in a php variable and echo it?
example:
602793420, 123870196, 416267436
You can get the productcode using explode() function, like this,
$product_code = explode("productcode: ", $option)[1];
Here's the reference:
explode()
So your code should be like this:
<?php
$content = $_POST;
for($i=1; $i < $content['itemCount'] + 1; $i++) {
$name = 'item_name_'.$i;
$quantity = 'item_quantity_'.$i;
$price = 'item_price_'.$i;
$image='item_image_'.$i;
$option='item_options_'.$i;
$product_code = explode("productcode: ", $option)[1];
$total = $content[$quantity]*$content[$price];
}
?>
I would rather suggest this, in case the option of the item will have more values in future.
$option = "image: CF01110.jpg, productcode: 123870196";
$options = explode(",", $option);
echo $product_code = explode("productcode: ", $options[1])[1];
Thanks
Amit

Sum and Average in multi-dimentional arrays with php

I'm trying to get sum and average of visitors from the following multi-dimensional array :
Array([visitors] => Array(
[2015-06-12] => Array([0] => Array([value] => 29))
[2015-06-11] => Array([0] => Array([value] => 55))
...
))
I cannot manage to find a way to get the results i need as i get lost with "foreach".
Can anybody help please ?
Use this
<?php
$mainarray = array('visitors' => Array(
'2015-06-12' => Array(Array('value' => 29)),
'2015-06-11' => Array(Array('value' => 55))));
$sum = 0;
$count = 0;
$visitor = $mainarray['visitors'];
foreach ($visitor as $key => $val) {
$sum += $val[0]['value'];
$count++;
}
echo "Sum is " . $sum."<br>";
$average = ($sum / $count);
echo "Average is " .$average."<br>";;
?>

(PHP) values of an array - recursion

After hours going around in circles I gave up and ask for help.
I have an array which looks like:
[field01] => Array
(
[name] => test01
[prefix] => C01
)
[field02] => Array
(
[url] => http://www.url.com
[user] => a_user
[password] => a_password
)
[filed03] => Array
(
[0] => Array
(
[id] => 1
[Type] => standard
[Name] => name
)
[1] => Array
(
[id] => 5
[Type] => standard
[Name] => name
)
)
Now I want to go through that array and get the following output as a return from a recursive function:
Array (
[0] = "The values of field01: name, prefix - test01, C01"
[1] = "The values of field02: url, user, password - http://www.url.com, a_user, a_password"
[2] = "The values of field03: id, Type, Name - 1, standard, name"
[3] = "The values of field03: id, Type, Name - 5, standard, name"
)
I have tried it with a recursive function but stuck with field03 to save the name.
Any help for that?
UPDTAE:
here is the array, so you don't have to write it:
$data['field01']['name'] = "field01";
$data['field01']['prefix'] = "C01";
$data['field02']['url'] = "http://www.url.com";
$data['field02']['user'] = "a_user";
$data['field02']['password'] = "a_password";
$data['field03'][0]['List_id'] = 1;
$data['field03'][0]['Type'] = "standard";
$data['field03'][0]['Name'] = "name";
$data['field03'][1]['List_id'] = 5;
$data['field03'][1]['Type'] = "standard";
$data['field03'][1]['Name'] = "name";
Thanks in advance!
<?php
$data['field01']['name'] = "field01";
$data['field01']['prefix'] = "C01";
$data['field02']['url'] = "http://www.url.com";
$data['field02']['user'] = "a_user";
$data['field02']['password'] = "a_password";
$data['field03'][0]['List_id'] = 1;
$data['field03'][0]['Type'] = "standard";
$data['field03'][0]['Name'] = "name";
$data['field03'][1]['List_id'] = 5;
$data['field03'][1]['Type'] = "standard";
$data['field03'][1]['Name'] = "name";
$text = '';
foreach ($data as $k => $fields) {
if (isset($fields[0])) {
foreach ($fields as $field) {
$text .= 'The values of ' . $k . ': ' . traverse($field) . "\n";
}
} else {
$text .= 'The values of ' . $k . ': ' . traverse($fields) . "\n";
}
}
echo $text;
function traverse($fields) {
$keys = array_keys($fields);
$values = array_values($fields);
return implode(', ', $keys) . ' - ' . implode(', ', $values);
}
?>
This assumes if there is an array of arrays, it is all arrays. In other words, you aren't mixing strings with arrays.
$resultArray = array();
function process($inputArray, $fieldName) {
$result = array();
$keys = array_keys($inputArray);
if (!is_array($inputArray[0])) {
$result[] = "The value of $fieldName: ".implode($keys,', '). ' - '. implode($inputArray, ', ');
} else {
foreach($inputArray as $arr) {
$result = array_merge($result, process($arr, $fieldName));
}
}
return $result;
}
foreach($data as $k=>$v) {
$processed = process($v, $k);
$resultArray = array_merge($resultArray, $processed);
}
print_r($resultArray);

Categories