Processing array and inserting in mysql table - php

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

Related

Write undefined number of form data to MySQL

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

Average result of multidimensional array in PHP

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

two dimensional array to Update into mysql database

I have this array:
Array (
[0] => Array
(
[0] => 2
)
[1] => Array
(
[0] => 2015-07-20
)
[2] => Array
(
[0] => 2
[1] => 5
)
[3] => Array
(
[0] => 70
[1] => 17
)
[4] => Array
(
[0] => 4
[1] =>
)
[5] => Array
(
[0] => 66
[1] => 17
)
)
Now I want Update to database like this
Array
(
[0] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 2
[3] => 70
[4] => 4
[5] => 66
)
[1] => Array
(
[0] => 2
[1] => 2015-07-20
[2] => 5
[3] => 17
[4] =>
[5] => 17
)
)
Is it possible? Or qny other way to UPdate record from array?
I have foreach loop OUTPUT like this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 item_id =5 before_sale_totitem_qty =70 before_sale_totitem_qty =17 after_sale_totitem_qty =4 after_sale_totitem_qty = restOfItem =66 restOfItem =17 note =NULL WHERE shop_id =2
But I Want to this:-
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =2 before_sale_totitem_qty =70 after_sale_totitem_qty =4 restOfItem =66 note =NULL WHERE shop_id =2
UPDATE update_shopwise_stock SET shop_id =2 datetime =2015-07-20 item_id =5 before_sale_totitem_qty =17 after_sale_totitem_qty = restOfItem =17 note =NULL WHERE shop_id =2
Any help?
If i understand your question you need transform data from first array to second array and after you can make this foreach?
If yes there is transform to array with default values from 0 index. Works for multiple versions so you can add index 3,5, etc. and it will works still.
$default = array();
$versions = array();
foreach($array as $key => $values){
foreach($values as $version => $value){
if($version === 0){
$default[$key] = $value;
continue;
}
if(!array_key_exists($version, $versions)){
}
$versions[$version][$key] = $value;
}
}
$return = array(
0 => $default,
);
foreach($versions as $version => $versionData){
$return[$version] = $versionData+$default;
}
If you need foreach to build your SQL query it is here to:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnData = array();
foreach($data as $columnIndex => $value){
$columnData[] = sprintf('%s = %s', $columns[$columnIndex], $value);
}
$sql = sprintf('UPDATE update_shopwise_stock SET %s WHERE shop_id=%d', implode(', ', $columnData), $data[0]);
}
But my personal recommendation is not use sql like this, but use PDO for prepare statement and better security. For prepare statement is for loop here:
$columns = array(
'shop_id', 'datetime', 'item_id', 'before_sale_totitem_qty', 'after_sale_totitem_qty', 'restOfItem'
);
foreach($return as $version => $data){
$columnPrepare = array();
$columnData = array();
foreach($data as $columnIndex => $value){
$columnName = $columns[$columnIndex];
$columnPrepare[] = sprintf('%s = :%s', $columnName, $columnName);
$columnData[$columnName] = $value;
}
$query = $db->prepare(sprintf("UPDATE update_shopwise_stock SET %s WHERE shop_id=:shop_id", implode(', ', $columnPrepare)));
foreach($columnData as $column => $value){
$query->bindParam(sprintf(':%s', $column), $value);
}
$query->execute();
}
Everything is untested and can have some bugs, eventually performance issue. It is based on question issue and show only way how to solve this issue.

php array_combine function is not working properly?

This is my code
$pro_qty = '';
$se_pro = '';
$pro_id_nn = $this->getDataAll("SELECT session_pro_id,session_pro_qty FROM `jp_session` WHERE session_pro_id IN (".$pro_id.") AND order_status='3'");
foreach($pro_id_nn as $pro)
{
$pro_qty[] = $pro['session_pro_qty'];
$se_pro[] = $pro['session_pro_id'];
}
$proqty = array_combine($pro_qty,$se_pro);
echo '<br>';
print_r($se_pro);
echo '<br>';
print_r($pro_qty);
echo '<br>';
print_r($proqty);
OUTOUT
first array
$se_pro = Array ( [0] => 5 [1] => 1 [2] => 1 ) ;
second array
$pro_qty = Array ( [0] => 24 [1] => 24 [2] => 22 ) ;
Finally combine two array result is
$proqty = Array ( [5] => 24 [1] => 22 );
but my expecting result is
$proqty = Array ( [5] => 24 [1] => 24 [1] => 22 );
how can i get my expecting result . thanks in advance.
Your expected result is not possible, you cannot map one key (1) to two different values (24 and 22). Perhaps you should look at a different solution, such as a "jp_session" class which contains the two values, and then just store it in a list.
simple solution
foreach($pro_id_nn as $pro)
{
$pro_qty[$pro['session_pro_id']][] = $pro['session_pro_qty'];
}
Try this one
<?php
$se_pro = Array ( 0 => 5, 1 => 1, 2 => 1 ) ;
$pro_qty = Array ( 0 => 24, 1 => 24, 2 => 22 ) ;
$a=sizeof($se_pro);
for($i=0;$i<$a;$i++)
{
$b=$se_pro[$i];
$c=$pro_qty[$i];
$temp[$b]=$c;
$i++;
}
print_r($temp);
?>
But one condition '$se_pro' values not repeat and both array are same size
in array_combine() If two keys are the same, the second one prevails..
you can get the result like -
Array
(
[24] => Array
(
[0] => 5
[1] => 1
)
[22] => 3
)
the other way can be
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
$output = array();
$size = sizeof($keys);
for ( $i = 0; $i < $size; $i++ ) {
if ( !isset($output[$keys[$i]]) ) {
$output[$keys[$i]] = array();
}
$output[$keys[$i]][] = $values[$i];
}
this will give the output like -
Array ( [24] => Array ( [0] => 5 [1] => 1 ) [22] => Array ( [0] => 1 ) )
or you can use
<?php
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $keys, $values);
print_r($arrResult);
?>
depending upon which output is more suitable for you to work with.

LAMP attendance system

i just cant get the right approach to this problem, i have two arrays .
first array $attendance which has the following keys and values
Array
(
[attendance] => Array
(
[1] => 1
[2] => 1
[3] => 0
[4] => 1
[5] => 1
[6] => 0
[7] => 0
)
This is coming from a checkbox if checked value is 1 else value is 0
The second array is $remark
[remark] => Array
(
[1] =>
[2] =>
[3] => 'sick'
[4] =>
[5] =>
[6] => 'leave'
[7] => 'On assignment'
)
Now this is what the key 1- 7 stands for, the script is for employee's attendance the key 1-7 is the employeeID in the employee table in my database.
Now what i want to achieve is concatenate the array in such a way to look like this
Array
(
[0] => Array
(
[employeeID] => 7
[attendance] => 0
[remark] => 'On assignment'
)
[1] => Array
(
[employeeID] => 6
[attendance] => 0
[remark] => 'leave'
)
[2] => Array
(
[employeeID] => 5
[attendance] => 1
[remark] =>
)
//and so on
)
I am using Codeigniter If i am able to concatenate it i will also love to know how i will insert the multiple data into the employee table which looks like this,
employee's table
employeeID | date | status | remarks
the date i planned using CURDATE() then status will hold either 0 or 1 from attendance
Again: the keys from 1- 7 both on the remark and attendance's array is the employeeID
update!!
this is what i tried but did not work.
$att = $_POST['attendance'];
$remarks = $_POST['remark'];
foreach($att as $employee_id=>$status)
{
$x=0;
$employee[$x]['employee_id']=$employee_id;
$employee[$x]['status']=$status;
foreach($remarks as $employee_id=>$remark)
{
$employee[$x]['remark']=$remark;
$x++;
}
}
$attendance = $_POST['attendance'];
$remarks = $_POST['remark'];
$collect = array();
foreach ($attendance as $employeeID => $attending) {
$collect[] = array(
"employeeID" => $employeeID,
"attendance" => $attending,
"remark" => isset($remarks[$employeeID]) ? $remarks[$employeeID] : ""
);
}
$values = array();
foreach ($collect as $entry) {
$values[] = "(" . ((int) $entry["employeeID"]) . ",
CURDATE(),
" . ((int) $entry["attendance"]) . ",
'" . sql_escape($entry["remark"]) . "'
)";
}
$query = "INSERT INTO `attendance`
(`employeeID`, `date`, `status`, `remarks`)
VALUES
(" . implode(",", $values) . ")";
Make sure you replace sql_escape by the appropriate escape function. If you're using PDO use that.
Easy enough, to be honest...
$numOfEmployees = 8;
$concatArray = array();
foreach($attendance as $k => $v)
{
$concatArray[] = array("employeeID" => $k, "attendance" => $v, "remark" => $remark[$k];
}
If your attendance table is in anything like SQL, you could go about it with foreach on the above mentioned concatArray:
foreach($concatArray as $key => $value)
{
$remark = $value['remark'];
// sanitize remark for database
$query = "INSERT INTO employees (ID, Date, Status, Remarks) VALUES ({$value['employeeID']}, NOW(), {$value['attendance']}, '{$value['remark']}');";
// perform the actual query
}
Keep in mind that this is a very general example, making a lot of assumptions about the database.
As Frits notes, the remark field should be sanitized, perhaps by using mysqli_real_escape_string for MySQLi or quote for PDO - depends on what you are using.

Categories