So I'm trying to get dynamic data from the $_POST array. The $_POST array looks like this after the form submit:
Array
(
[teams1member3] => on
[teams1member4] => on
[teams1member7] => on
[teams1member8] => on
[teams2member1] => on
)
Now I'm not entirely sure how I can access these, the teams can be any number and the same goes for a member. Is there a way to "read" the [teams1member3]?
I tried looping through the $_POST variable with a foreach loop (foreach($_POST as $post)), but this only gets the value (on). If I'm able to get the teams1member3, teams1member4, etc. I should be able to continue.
Anyone that can help me out? Much appreciated!
You should use the $key => $value syntax:
foreach($_POST as $key => $post){
// $key is what you need
}
But you should rather serialise your $_POST data better, consider using the following JSON notation:
{
"teams" : [
{
"id": 1,
"members": [3, 4, 7, 8]
},
{
"id": 2,
"members": [1]
}
]
}
foreach ($_POST as $key => $value) {
// ...
}
$key will contain array keys (what you need), $value - string "on".
if you just use foreach($_POST as $value) , you will only get the values - in your case on and off
However, if you want the actual field name, you have to specify key and value in your foreach:
foreach($_POST a $key => $value) {
//$key contains teammember
//$value contains on
}
Related
There are two arrays:
$arr1 = [
"Value1",
"Value2",
"Value1"
];
$arr2 = [
["key_1" => "5", "key_2" => "10"], // relates to Value1
["key_1" => "2", "key_2" => "4"], // relates to Value2
["key_1" => "50", "key_2" => "100"] // relates to Value1
];
I cannot simply combine the two arrays because the duplicated values in $arr1 will lead to overwritten data from $arr2.
The behavior that I need is for subarray data to be added if a value from $arr1 is encountered more than once.
I tried to find all sorts of folding options while searching the web, but I could find anything that was right.
I need this output from the sample input arrays:
array (
'Value1' =>
array (
'key_1' => 55,
'key_2' => 110,
),
'Value2' =>
array (
'key_1' => '2',
'key_2' => '4',
),
)
I've tried to write a solution, but I'm not really sure how to tackle the problem.
foreach ($items as $item) {
if (isset($bal[$item['bonus_name']])) {
//Here I don't know how to sum a new one to the repetition?
} else {
$bal[$item['bonus_name']] = $item['bonus_count'];
}
}
Whatever I try, there's no way to sum a repetitive array of elements. I need some help.
Loop the first array to declare the index -> group relationship.
Check if the currently encountered group is unique to the output array. If so, push the entire subarray from the corresponding index in the second array into the output array as the initial values of the group.
If the group is encountered more than once, add each column value to the related amount in the group's subarray.
Code: (Demo)
$result = [];
foreach ($arr1 as $index => $group) {
if (!isset($result[$group])) {
$result[$group] = $arr2[$index];
} else {
foreach ($arr2[$index] as $key => $value) {
$result[$group][$key] += $value;
}
}
}
var_export($result);
How to get the contact values?, and How are the values stored in php?
{
_id : "001",
name : "fakename",
contact_address : {
street : "12 Street",
city : "Cosmos",
contact : [
"123456789",
"012345678"
]
}
}
Query :
$cursor = $collection->find ( array('name' => 'fakename' ), array( 'contact_address.contact' ) );
foreach ( $cursor as $doc ) {
echo $doc[ 'contact_address' ][ 'contact' ];
}
Result :
Array
Motive : Intend to print the contact values.
To print array values you can use print_r, var_dump or var_export - for debugging purposes.
To iterate them and use values in other places - you can use for example foreach like that:
foreach ($array as $key => $value) {
// $key holds the index, $value holds the value of the array
}
There are other ways to iterate array, in fact way too many in PHP, but this should suffice.
I need to do "foreach" action only for the highest parent nodes in my PHP array.
In this example I would like to get echo of the family lastnames...
$families = array(
'Brooks' => array(
'John',
'Ilsa',
),
'Hilberts' => array(
'Peter',
'Heidy',
));
foreach($families as $family){
// do some action that will return only "Brooks,Hilbers"
// not "Brooks,John,Ilsa,Hilbers,Peter,Heidy,Brooks,John,Ilsa,Hilberts,Peter,Heidy"
}
Is is handable, or should I define the array differently? Thank you very much for any positive answer.
You can simply return the key of the array (which is the family name):
foreach($families as $key => $family){
echo "FAMILY NAME = ".$key;
}
You can use the foreach just like ($array as $value) or like ($array as $key => $value). When the array is indexed (numerical key) the $key returns the position of the index (0, 1, 2...). When the array is associative (named keys), the $key returns the name of the index (in your example, Brooks, Hilberts, ...)
For more information please see PHP Arrays and Foreach Manual
I have the following associative array stored in a php file also containing a database connect statement.
$fields = array(
"A" => "A",
"B" => "B",
"C" => "C",
...
);
Here I am calling it
include('dbconnection.php');
What I intended from this code is that the $field values within $_POST[$field] would be transferred over to values stored within $fields.
if (isset($_POST['submit'])){
//iterating through fields array
foreach($fields as $column => $field){
//cleaning and storing user input in fields array
$field = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$field]));
}
These new $fields array values would then be transferred over to $emptyArray, where elements of the array containing 0, NULL, FALSE, or "" values would be filtered out.
$emptyArray = array();
$emptyArray = array_merge ($emptyArray, array_values($fields));
$emptyArray = array_filter($emptyArray);
Finally, after checking if there were any elements stored in $emptyArray, an error message would be issued, along with a call to run function renderform.
if (empty($emptyArray)){
$error = 'You have reached this message because you did not specify a field to update';
renderForm($id, $fields, $error);
}
}
function renderform contains the argument $fields, the first array in this chain, which is why I chose to use $emptyArray instead of $fields in order to conserve its structure.
However, if I run print_r of $fields and $emptyArray immediately before renderform, I receive arrays identical to keys and values stored in $fields prior to their manipulation
Array ( [A] => A [B] => B [C] => C [...] => ...)
Can I use $_POST[$field] in the way that I'm intending ($field values within $_POST[$field] being transferred over to values stored within $fields)? If so, is this good practice?
Thanks for reading,
I'm happy to answer any questions.
You could do this in a single loop:
$fields = array(
"A" => "A",
"B" => "B",
"C" => "C",
);
$post=[];
foreach($fields as $key => $val){
if(!isset($_POST[$key]) || !$_POST[$key]){
die("data for $key is incorrect or missing");
}
$post[$key] = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$key]));
}
//all is fine, use $post array for whatever you need it for
The Problem
I would like to create a new associative array with respective values from two arrays where the keys from each array match.
For example:
// first (data) array:
["key1" => "value 1", "key2" => "value 2", "key3" => "value 3"];
// second (map) array:
["key1" => "map1", "key3" => "map3"];
// resulting (combined) array:
["map1" => "value 1", "map3" => "value 3"];
What I've Tried
$combined = array();
foreach ($data as $key => $value) {
if (array_key_exists($key, $map)) {
$combined[$map[$key]] = $value;
}
}
The Question
Is there a way to do this using native PHP functions? Ideally one that is not more convoluted than the code above...
This question is similar to Combining arrays based on keys from another array. But not exact.
It's also not as simple as using array_merge() and/or array_combine(). Note the arrays are not necessarily equally in length.
You can use array_intersect_key() (http://ca2.php.net/manual/en/function.array-intersect-key.php).
Something like that:
$int = array_intersect_key($map, $data);
$combined = array_combine(array_values($map), array_values($int));
Also it would be a good idea ksort() both $map and $data.