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.
Related
I need to make my array better.
I am getting data from database and i have milestones and milestone_parts. i want two-dimensional array. I need data of milestones in the first dimension and milestone_parts in the second dimension.
With this code:
$query = "
SELECT
a.id AS `milestone_id`,
a.titel AS `milestone_titel`,
a.client AS `client`,
a.verkocht_id AS `milestone_verkocht_id`,
b.id AS `milestonefase_id`,
b.titel AS `milestonefase_titel`,
b.milestone_id AS `milestonefase_milestone_id`,
b.omschrijving AS `milestonefase_omschrijving`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '99'
";
$result= $db->query($dbh, $query);
while ($row = $db->fetchassoc($result))
{
$stone = array($row['milestone_verkocht_id'], $row['milestone_id'], $row['milestone_titel'], $row['client']);
$fase = array($row['milestonefase_milestone_id'],$row['milestonefase_id'],$row['milestonefase_titel']);
$stone[] = $fase;
echo '<pre>'; print_r($stone); echo '</pre>';
}
I get this as result
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 10
[2] => string
)
)
Array
(
[0] => 99
[1] => 6
[2] => string
[3] => string
[4] => Array
(
[0] => 6
[1] => 11
[2] => string
)
)
but I need (with names) this:
Array
(
[milestone_verkocht_id] => 99 // This is project id
[milestone_id] => 6
[milestone_title] => string
[client] => string
[10] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 10
[milestone_title] => string
)
[11] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 11
[milestone_title] => string
)
[12] => Array
(
[milestonefase_milestone_id] => 6
[milestonefase_id] => 12
[milestone_title] => string
)
)
Can you help me or do you have a solution? Help me please!
you can cycle each field returned by the query, checking the field name and making new arrays
$stones = array();
while ($row = $db->fetchassoc($result)) {
$fase = array();
$stone = array('milestones' => array());
foreach ($row as $k => $v) {
if (strpos($k, 'milestonefase_') === 0) {
$fase[$k] = $v;
} else {
$stone[$k] = $v;
}
}
if(!isset($stones[$stone['milestone_id']])) {
$stones[$stone['milestone_id']] = $stone;
}
$stones[$stone['milestone_id']]['milestones'][$fase['milestonefase_id']] = $fase;
}
echo '<pre>'.print_r($stones, true).'</pre>';
Edit
made some changes in order to match the request. Now we use $stones to store the information we already have on a milestone, adding to it the different "$fase" returned from the query
Probably a more clean way is to retrieve all the information with two different queries one for milestones and the other for the fases
Edit2
Added a sub-array for the milestone fases
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'm using PHP in doing our exercise which is to get the necessary details of a user and the quiz he/she took.
This is my code so far.
<?php
require("dbOption/Db.class.php");
$db = new Db();
$data = array();
$quiz = array();
$easy = "";
$normal = "";
$hard = "";
// SELECT id, course FROM quizz WHERE course = 2
$res_quizz = $db->query("SELECT id, course FROM quizz WHERE course = :course", array("course"=>2));
foreach ($res_quizz as $key => $value) {
$quizzid = $value['id'];
// SELECT easy, normal, hard, userid FROM quizzscore WHERE quizid = $quizid
$res_quizzscore = $db->query("SELECT easy, normal, hard, userid, quizzid FROM quizzscore WHERE quizzid = :quizzid", array("quizzid"=>$quizzid));
foreach ($res_quizzscore as $key => $value2) {
$easy = $value2['easy'];
$normal = $value2['normal'];
$hard = $value2['hard'];
$quizzid = $value2['quizzid'];
$userid = $value2['userid'];
$q = array(
'Qz'.$quizzid => array(
'easy' =>$easy,
'normal' =>$normal,
'hard' =>$hard,
)
);
$quiz['quizzes'] = $q;
// SELECT name FROM USER WHERE id = $userid
$res_user = $db->query("SELECT name FROM user WHERE id = :id", array("id"=>$userid));
foreach ($res_user as $key => $value3) {
$name = $value3['name'];
}
}
$data[$userid] = array();
$data[$userid]['name'] = $name;
$data[$userid]['quizzes'] = $quiz;
echo "<pre>";
print_r($data);
echo "<pre/>";
}
The array is poorly manipulated and that's why I'm getting this result.
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz1] => Array
(
[easy] => 5
[normal] => 6
[hard] => 7
)
)
)
)
)
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz2] => Array
(
[easy] => 3
[normal] => 4
[hard] => 5
)
)
)
)
)
What I want to have is this kind of result.
Array
(
[1] => Array
(
[name] => John Smith
[quizzes] => Array
(
[quizzes] => Array
(
[Qz1] => Array
(
[easy] => 5
[normal] => 6
[hard] => 7
)
[Qz2] => Array
(
[easy] => 3
[normal] => 4
[hard] => 5
)
)
)
)
)
Any ideas would be most appreciated.
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.
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);
}