Good Afternoon.
I'm attempting to make an array list with one of the key values being ($_REQUEST['qty#']), where "#" would be the current number of the item within the array (as it pertains to a field in a form that gathers this info).
For example:
$itemdetails = array(
array(
'qty' => ($_REQUEST['qty1']),
'price' => 0.70,
'pn' => 'TV-1000',
array(
'qty' => ($_REQUEST['qty2']),
'price' => 0.99,
'pn' => 'TV-5000'));
Is there any way that I can automatically have the number in ($_REQUEST['qty']) be determined without having to type in the numbers manually?
Just wondering. My next guess would be to enter it all into a database and pull it from there.
Thanks a bunch in advance.
You would need to loop ...
$itemdetails = array(
array(
'price' => 0.70,
'pn' => 'TV-1000'
),
array(
'price' => 0.99,
'pn' => 'TV-5000'
)
);
foreach ( $itemdetails as $k => &$item ) {
$item['qty'] = $k + 1;
}
What you should do is pass an array of data via POST/GET.
To do this in your inputs, you make the name value = qty[] for each input. Note the array syntax [] here.
PHP will automatically take all values for input with that array syntax and build an array out of it in $_POST/$_REQUEST.
So you would be able to access your array like
var_dump($_POST['qty']);
var_dump($_REQUEST['qty']);
That however still doesn't give the ability to match this to the price/pn as you need. So, let's take the array syntax one step further and actually put a key value in it like this:
<input name="qty[0]" ... />
<input name="qty[1]" ... />
By doing this you will be able to know exactly which array index matches which item (assuming you know the order the inputs were displayed in).
The would make $_POST['qty'][0] be the first item, $_POST['qty'][1] be the next and so on.
So assuming you also have you prices/pn in an array like this:
$item_array = array(
0 => array('price' => 123, 'pn' = 'ABC'),
1 => array('price' => 456, 'pn' = 'XYZ'),
...
);
You could then easily loop through the input quantities and build you final array like this:
$itemdetails = array();
foreach ($_REQUEST['qty'] as $key => $value) {
$itemdetails[$key] = $item_array[$key];
$itemdetails[$key]['qty'] = $value;
)
Also note, that if you are expecting this data to be passed via POST, it is considered best practice to use the $_POST superglobal rather than the $_REQUEST superglobal.
Related
This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 4 months ago.
I have an array in my php code
$list = array(
'RETAIL' => 'SUPERMARKET'
'RETAIL' => 'BAR'
'RETAIL' => 'DEP. MARKET'
'BUSINESS' => 'HOTEL'
'BUSINESS' => 'PUB'
'OTHER' => 'GROCERY'
'OTHER' => 'BUTCHERY'
// I have 20+ items
);
foreach( $list as $type => $name ){
var_dump($type,$name);
}
//var_dump() output
// RETAIL SUPERMARKET
// BUSINESS HOTEL
// OTHER BUTCHERY
I'm facing the problem that when I try to loop the array only three values will be returned and the rest are ignored. How I can fix this?
I'm trying to loop the array to save the data into a custom wordpress database. With the same way I've successfully looped another array inserted the keys and values into the db.
I think a better structure for your array would something like this
$list = [
'RETAIL' => [
'BAR',
'RESTAURANT'
]
];
And you could loop over like so
foreach ($list as $businessType => $businesses) {
foreach ($businesses as $business) {
echo "<li>{$business}</li>";
}
}
Just an example
As a general way of handling instances where you have more than one element to each piece of data (even when it's not in a tree structure like this may be), you should structure each item in the list as either an array or object, eg:
$list_of_arrays = [
['RETAIL', 'SUPERMARKET'],
['RETAIL', 'BAR'],
['RETAIL', 'DEP. MARKET'],
];
foreach( $list_of_arrays as $array ){
echo "<li>{$array[0]} {$array[1]}</li>";
}
or
$list_of_objects = [
(object)['type' => 'RETAIL', 'subtype' => 'SUPERMARKET'],
(object)['type' => 'RETAIL', 'subtype' => 'BAR'],
(object)['type' => 'RETAIL', 'subtype' => 'DEP. MARKET'],
];
foreach( $list_of_objects as $object ){
echo "<li>{$object->type} {$object->subtype}</li>";
}
Maybe I show heavily but as you only have two data for each entity, why your table is not built like this at the base...?
$list = array(
'SUPERMARKET'=>'RETAIL',
'BAR'=>'RETAIL',
'DEP. MARKET'=>'RETAIL',
'HOTEL'=>'BUSINESS',
'PUB'=>'BUSINESS',
'GROCERY'=>'OTHER',
'BUTCHERY'=>'OTHER'
// I have 20+ items
);
You do have keys that uniquely identify entities.
Working with an array file with following structure. I know there are additional arrays that need to be inserted under each array 'color'.
$items=array (
0 =>
array (
'color' => 'category_a',
),
1 =>
array (
'book' => 'Gone With The Wind',
'movie' => 'GWTW',
'id'=> 'A100'
),
2 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'A103'
),
3 =>
array (
'color' => 'category_b',
),
4 =>
array (
'book' => 'Across The Great Dvide',
'movie' => 'ATGD',
'id'=> 'B102'
),
5 =>
array (
'book' => 'Goldfinger',
'movie' => 'GF',
'id'=> 'B103'
),
);
Once this array is created, I am using a list to loop thru to verify that each value in the list is placed in each 'color' array as follows
foreach ($controllist as $key=>$value){
foreach($items as $item){
if(in_array($value['book'],$item){
echo "PRESENT IN ARRAY"."<BR>";
}else{
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
For simplicity my controllist looks like
Gone With The wind
Across The Great Divide
Goldfinger
Once complete I should end up with the info for Across The Great Divide inserted into 'color'=> 'category a' as the [2] with Goldfinger moving down one. In 'color'=>category_b' the first array should be Gone With The Wind. Any of the 'color' arrays could be missing an array at any position. To sum it up, need to check for the existence of a value from the list, if not present insert into the array. Other than using the foreach loops shown is there an easier way of doing this? If not how can I get the information inserted into the proper position?
Thanks
EDIT:
I believe the question may not be clear. What I need to do is check for the existence of one array in another. If the value in conrollist is not present in the array, insert an array into the array according the position in the conrollist. The inserted array will have the same structure as the others (I can take care of this part). I am having trouble determining if it exist and if not inserting it. Hope this helps
You might want to be using a for loop instead so you have a pointer on each iteration in order to determine where you are in the array.
foreach($items as $item){
for($i = 0; $i < count($controllist); $i++) {
if(in_array($controllist[$i]['book'],$item){
echo "PRESENT IN ARRAY AT POS ".$i."<BR>";
}else{
$controllist[$i]['book'] = $yourvar;
echo "INSERT INTO ARRAY HERE"."<BR>";
}
}
}
What do
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
mean?
Thanks a lot.
How should i format the output so i can learn the results that was returned?
You can format your code into tables by looping on the array using for or foreach. Read the docs for each if you don't have a grasp on looping.
2.What does
$categories[$id] = array('name' => $name, 'children' => array());
and
$categories[$parentId]['children'][] = array('id' => $id, 'name' => $name);
The first line assigns an associative array to another element of the $categories array. For instance if you wanted the name of the category with ID of 6 it would look like this:
$categories[6]['name']
The second line does something similar, except when you are working with an array in PHP, you can use the [] operator to automatically add another element to the array with the next available index.
What is the uses of .= ?
This is the concatenation assignment operator. The following two statements are equal:
$string1 .= $string2
$string1 = $string1 . $string2
These all have to do with nesting arrays.
first example:
$categories[$id] = array('name' => $name, 'children' => array());
$categories is an array, and you are setting the key id to contain another array, which contains name and another array. you could accomplish something similar with this:
$categories = array(
$id => array(
'name' => $name,
'children' => array()
)
)
The second one is setting the children array from the first example. when you have arrays inside of arrays, you can use multiple indexes. It is then setting an ID and Name in that array. here is a another way to look at example #2:
$categories = array(
$parentID => array(
'children' => array(
'id' = $id,
'name' => $name
)
)
)
note: my two ways of rewriting are functionally identical to what you posted, I'm just hoping this makes it easier to visualize what's going on.
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.
I have a POST request coming to one of my pages, here is a small segment:
[shipCountry] => United States
[status] => Accepted
[sku1] => test
[product1] => Test Product
[quantity1] => 1
[price1] => 0.00
This request can be any size, and each products name and quantity's key would come across as "productN" and "quantityN", where N is an integer, starting from 1.
I would like to be able to count how many unique keys match the format above, which would give me a count of how many products were ordered (a number which is not explicitly given in the request).
What's the best way to do this in PHP?
Well, if you know that every product will have a corresponding array key matching "productN", you could do this:
$productKeyCount = count(preg_grep("/^product(\d)+$/",array_keys($_POST)));
preg_grep() works well on arrays for that kind of thing.
What Gumbo meant with his "use array instead" comment is the following:
In your HTML-form use this:
<input type="text" name="quantity[]" />
and $_POST['quantity'] will then be an array of all containing all of your quantities.
If you need to supply an id you can also do this:
<input type="text" name="quantity[0]" />
$_POST['quantity][0] will then hold the corresponding quantity.
As mentioned by gumbo you could group all parameters describing one item in its own array which usually makes it easier to iterate them. You may not have control over the POST parameters but you can restructure them like e.g. with
<?php
$testdata = array(
'shipCountry' => 'United States',
'status' => 'Accepted',
'sku1' => 'test1',
'product1' => 'Test Product1',
'quantity1' => '1',
'price1' => '0.01',
'sku2' => 'test2',
'product2' => 'Test Product2',
'quantity2' => '2',
'price2' => '0.02'
);
$pattern = '/^(.*\D)(\d+)$/';
$foo = array('items'=>array());
foreach($testdata as $k=>$v) {
if ( preg_match($pattern, $k, $m) ) {
$foo['items'][$m[2]][$m[1]] = $v;
}
else {
$foo[$k] = $v;
}
}
print_r($foo);
Though there be plenty of examples, if you're guaranteed that the numbers should be contiguous, I usually take the approach:
<?php
$i = 1;
while( isset($_POST['product'.$i) )
{
// do something
$i++;
}