I'm trying now for a while to wrap my head around the following:
I've got a form that submits a user defined number of values to a PHP script and I need to write them into a MySQL database.
The form itself is working fine and print_r() shows my values like this:
[items] => Array
(
[1] => Array
(
[option] => 3
[check_1] => 1
)
[2] => Array
(
[option] => 2
[check_1] => 1
)
[17] => Array
(
[check_1] => 1
[check_3] => 1
)
)
There will be one option value and up to ten checkboxes per item. Now I'd need to end up with something like this to write each item to the DB:
INSERT INTO table (item_id, option, check_1, check_2,...)
VALUES ('$ItemID', '$OptionValue', '$Check_1_Value', '$Check_2_Value',...)
My biggest problem is to read out the Item IDs (1,2 and 17 in this case) and get it into variables.
Help at PHP : foreach.
foreach ( $items as $key => $values )
{
// $key => 17 <= this the values you were looking for
// $values => { [check_1] => 1, [check_3] => 1 }
[...]
}
Init array:
$items = array(
1 => array(
"option" => 3,
"check_1" => 1,
),
2 => array(
"option" => 2,
"check_1" => 1,
),
17 => array(
"check_1" => 1,
"check_3" => 1,
),
) ;
Parse array:
foreach( $items as $k1 => $a1 )
{ // should be escape for safety mysql_real_escape() or ...
$dbCols = "item_id";
$dbValues = $k1;
foreach( $a1 as $k2 => $v2 )
{
$dbCols .= ",$k2";
$dbValues .= ",$v2";
}
echo "INSERT INTO `table` ( $dbCols ) VALUES ( $dbValues );\n";
}
Result:
INSERT INTO `table` ( item_id,option,check_1 ) VALUES ( 1,3,1 );
INSERT INTO `table` ( item_id,option,check_1 ) VALUES ( 2,2,1 );
INSERT INTO `table` ( item_id,check_1,check_3 ) VALUES ( 17,1,1 );
Related
I have following query in loop for select records
$shopchairs=$rows['shop_chairs']; //coming dynamically i.e. 1 or 3 or 4
$result = [];
for($i=1;$i<=$shopchairs;$i++)
{
$query = //SELECT QUERY WITH WHERE CONDITION;
$res = $query->result_array();
$result[] = [
'chairnumber' => $i,
'status' => $querys->num_rows() > 0 ? 'booked' : 'available',
'estimateTime' => "",
];
}
echo "<pre>";print_R($result);
Now I just want to merge "estimateTime" which is coming from $res(array) with $result(array), How can I do this?
Right now my $res showing following array in the loop
Array
(
[0] => Array
(
[shopId] => 2
[duration] => 20
[estimatedTime] => 11.3000
)
)
Array
(
)
Array
(
)
Array
(
)
I just want to merge estimatedTime with $result array
This is a question for all the array specialists out there. I have an multi dimension array with a result as number (can be 0,1 or 2) and need the average for each grouped by parent.
In the example below the calculation would be:
subentry1_sub1 = 2 + 2 = 4 (4/2=2)
subentry1_sub2 = 1 + 1 = 2 (2/2=1)
So what I try to archive in PHP is the following result:
subentry1_sub1 average = 2
subentry1_sub2 average = 1
...
I already tried some solutions from similar questions. But with all the recursive functions I didn't managed to get it aggregated by the last child name (e.g. subentry1_sub1).
Any ideas?
EDIT:
subentry1_sub1 is 2 + 2 because its two times in the array
[entry1] => [subentry1] => [subentry1_sub1] => result
[entry2] => [subentry1] => [subentry1_sub1] => result
Array
(
[entry1] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
[entry2] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
)
Try this code. In this i have created a new array $sum which will add result value of same subentry childs with same key and another array $count which will count the number of times each key repeats
<?php
$data = array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
)
);
$sum = array();
$repeat = array();
foreach($data as $input){
foreach($input as $array){
foreach($array as $key=>$value){
if(array_key_exists($key,$sum)){
$repeat[$key] = $repeat[$key]+1;
$sum[$key] = $sum[$key] + $value['result'];
}else{
$repeat[$key] = 1;
$sum[$key] = $value['result'];
}}}}
echo "<pre>";
print_r($sum);
print_r($repeat);
foreach($sum as $key=>$value){
echo $key. ' Average = '. $value/$repeat[$key]."</br>";
}
Output
Array
(
[subentry1_sub1] => 4
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
Array
(
[subentry1_sub1] => 2
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
subentry1_sub1 Average = 2
subentry1_sub2 Average = 1
subentry2_sub1 Average = 1
subentry2_sub2 Average = 1
You can easily calculate avg now
Note : As you mentioned you are counting occurence of subentry1_sub1 etc so i did the same so it will also count whether key result exists or not
I know this is an old thread but im pretty sure there is a much easier way of doing this for anyone who is interested:
If you know the result will always be a number:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_column($sub_data, 'result');
$averages[$entry_name][$sub_name] = array_sum($sub_results)/count($sub_results);
}
}
If its possible the result could be NULL or empty, this will check it and return 'N/A' if there is no valid data to calculate an average from:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_filter(array_column($sub_data, 'result'));
$averages[$entry_name][$sub_name] = (count($sub_results) > 0 ? array_sum($sub_results)/count($sub_results) : 'N/A');
}
}
both of these solutions will give you an averages array that will output the average per subentry per entry.
Try this like,
<?php
$data=array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>3),
'subentry1_sub2'=>array('value'=>'abc','result'=>3)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>2),
'subentry2_sub2'=>array('value'=>'abc','result'=>8)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>6),
'subentry1_sub2'=>array('value'=>'abc','result'=>6)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>10),
'subentry2_sub2'=>array('value'=>'abc','result'=>12)
)
)
);
foreach($data as $k=>$v){
echo "----------------$k---------------------\n";
if(is_array($v)){
foreach($v as $a=>$b){
if(is_array($b)){
echo $a.' average = ';
$c=array_keys($b);// now get *_sub*
$v1=isset($b[$c[0]]['result']) ? $b[$c[0]]['result'] : '';
$v2=isset($b[$c[1]]['result']) ? $b[$c[1]]['result'] : '';
echo ($v1+$v2)/2;
echo "\n";
}
}
}
}
Online Demo
In the meantime I found a simple working solution myself:
foreach ($data as $level2) {
foreach ($level2 as $level3) {
foreach ($level3 as $keyp => $level4) {
foreach ($level4 as $key => $value) {
if($key == 'result') $stats[$keyp] += $value;
}
}
}
}
With that you get the total for every key in an new array $stats.
But be sure to checkout the solution from user1234, too. It's working great and already includes the calculation of the average.
https://stackoverflow.com/a/39292593/2466703
I've got a dynamic form that allows a user to create as many form elements as they need -- then submit them. For this, I have prepared the input names as arrays like
<input name="title[]" ...
and posting them gives me output like
Array
(
[day] => 0
[project_id] => 5
[submit] => publish
[id] => Array
(
[0] => 4
[1] => 5
)
[title] => Array
(
[0] => Step 1
[1] => Step 2
)
[max_vol] => Array
(
[0] => 2
[1] => 3
)
[description] => Array
(
[0] => df dofi dofidfoi
[1] => dfvpdofvdpfo osd pod
)
)
I've created something that allows me to just grab the post arrays like so
foreach( $_POST as $post_key ) {
// ignore non-array post variables
if( is_array( $post_key ) ) {
foreach( $post_key as $form_value ) {
echo "$form_value\n";
}
}
}
/* ouputs...
4
5
Step 1
Step 2
2
3
df dofi dofidfoi
dfvpdofvdpfo osd pod
*/
which nicely sorts the non-arrays from the arrays, but I can't figure out how to take this variable number of created form elements and prepare them into an array variable that looks something like...
Array
(
[0] => Array
(
'id' => 4, 'title' => 'Step 1', 'max_vol' => '2', 'description' => 'df dofi dofidfoi'
),
[1] => Array
(
'id' => 5, 'title' => 'Step 2', 'max_vol' => '3', 'description' => 'dfvpdofvdpfo osd pod'
),
// could be more or less elements...
);
(I will be eventually passing these arrays to a MySQL query builder function).
Thanks.
How about creating a variable that is outside the scope of the foreach loop
$results = array();
foreach( $_POST as $post_key=>$post_value ) {
// ignore non-array post variables
if( is_array( $post_value ) ) {
foreach( $post_value as $form_key=>$form_value ) {
if (!isset($results[$form_key]))
{
$results[$form_key] = array();
}
$results[$form_key][$post_key] = $form_value;
}
}
}
// results is your array variable
print_r($results);
Iterate over some significant $_POST-array key, for example - id and get the values from other $_POST-arrays with the same index:
$values = array();
foreach ($_POST['id'] as $k => $v) {
$values[] = array(
'id' => $v,
'title' => $_POST['title'][$k],
'max_vol' => $_POST['max_vol'][$k],
'description' => $_POST['description'][$k],
);
}
print_r($values);
Array
(
[pid] => Array
(
[0] => 2
[1] => 3
)
[price] => Array
(
[0] => 20
[1] => 20
)
[qty] => Array
(
[0] => 2
[1] => 1
)
)
i have an outcome of the above array from some processing. with this i need to update to database like below table
pid price qty
2 20 2
3 20 1
$i = 0;
while( $i < count( $YourArray['pid']) ) {
$query = "INSERT INTO `tableName`(`pid`, `price`, `qty`) VALUES( ?, ?, ? )";
$stmt = $con->prepare( $query );
$stmt->execute(
array(
$YourArray['pid'][$i],
$YourArray['price'][$i],
$YourArray['qty'][$i]
)
);
$i++;
}
Where, I used the pdo method of insertion.
for(i=0;i<amount;i++){
echo $array['pid'][i];
echo $array['price'][i];
echo $array['qty'][i];
}
Where amount must be a count of the amount of rows you have
Try this :
$array = array("pid" => array(2,3),"price" => array(20,20),"qty" => array(2,1));
array_unshift($array, null);
$res = call_user_func_array('array_map', $array);
echo "<pre>";
print_r($res);
Output :
Array
(
[0] => Array
(
[0] => 2
[1] => 20
[2] => 2
)
[1] => Array
(
[0] => 3
[1] => 20
[2] => 1
)
)
loop this array and add to DB - So that you can add two entries in DB
this is a wrong way of doing it, i would use an indexed array, and then build a foreach loop that will handle each 1 separately, something like:
$values = array();
$values[] = array(
'pid' => 2,
'price' => 20,
'qty' => 2
);
$values[] = array(
'pid' => 3,
'price' => 20,
'qty' => 1
);
and from this then build a foreach loop and run each query there
foreach ($values as $value) {
$query = "insert into blah
set pid = " . $value['pid'] . ",
price = " . $value['price'] . ",
qty = " . $value['qty'] . ";";
mysql_query($query);
}
I have something similar to the following structure:
Array
(
[wp_postmeta] => Array
(
[0] => stdClass Object
(
[meta_id] => 1
[post_id] => 2
[meta_key] => _wp_page_template
[meta_value] => default
)
)
[wp_comments] => Array
(
[0] => stdClass Object
(
[comment_ID] => 1
[comment_post_ID] => 1
[comment_author] => Mr WordPress
[comment_author_email] =>
[comment_author_url] => http://wordpress.org/
[comment_author_IP] =>
[comment_date] => 2011-10-20 03:06:23
[comment_date_gmt] => 2011-10-20 03:06:23
[comment_content] => Hi, this is a comment.
[comment_karma] => 0
[comment_approved] => 1
[comment_agent] =>
[comment_type] =>
[comment_parent] => 0
[user_id] => 0
)
)
)
What I'm trying to do here is iterate over these results so I can use them to form a query.
Assume all the data within the wp_postmeta table is deleted from the database and this array contains the data of that table before it was deleted. I want to take this saved data in the array and reset the table with these old values.
I.e Looping through the array and inserting this as sql: INSERT INTO wp_postmeta (meta_id, post_id, meta_key, meta_value) VALUES (1, 2, '_wp_page_template', 'default')
foreach ($outerArray as $tableName => $tableData) { // Loop outer array
foreach ($tableData as $row) { // Loop table rows
$cols = $vals = array();
foreach ($row as $col => $val) { // Loop this row
$cols[] = $col;
$vals[] = $val; // You may need to escape this before using it in a query...
}
// Build the query
$query = "INSERT INTO $tableName (".implode(', ',$cols).") VALUES ('".implode("', '",$vals)."')";
// Do the query here
}
}
You can iterate over object properties just like you can with an array, and in a stdClass everything is public, so the above should work no problem.