is there anyone know how to format this array in a loop so that it will insert in a database in a single query but in a loop way using php.
I'm making a multiple form by the way.
here's the array format of the field and this is my form looks like attendance
Array
(
[sup_payroll_type] => Array
(
[0] => 1
[1] => 2
[2] => 1
)
[sup_month] => Array
(
[0] => January
[1] => January
[2] => May
)
[sup_year] => Array
(
[0] => 2015
[1] => 2015
[2] => 2015
)
[sup_late_days] => Array
(
[0] => 1
[1] => 1
[2] => 2
)
[sup_absent_days] => Array
(
[0] => 2
[1] => 1
[2] => 0
)
[sup_id] => Array
(
[0] => 1
[1] => 5
[2] => 6
)
[sup_emp_id] => Array
(
[0] => 24
[1] => 24
[2] => 24
)
[save_edit_satt] => Array
(
[0] => SAVE
)
)
any help would be appreciated.
Please try below loop:-
$insertQuery = 'INSERT INTO attendence (sup_payroll_type, sup_month, sup_year,
sup_late_days, sup_absent_days, sup_id, sup_emp_id,
save_edit_satt) VALUES';
foreach($attendenceArray AS $key => $value){
$insertQuery .= '("'.$value['sup_payroll_type'].'","'.$value['sup_month'].'",
"'.$value['sup_year'].'","'.$value['sup_late_days'].'",
"'.$value['sup_absent_days'].'","'.$value['sup_id'].'",
"'.$value['sup_emp_id'].'","'.$value['save_edit_satt'].'"),';
}
$insertQuery = rtrim($insertQuery,',');
$insertQuery contains ur insert query.
$attendenceArray contains ur example array.
If ur using mysqli then used mysqli_query($mysqli,$insertQuery) to execute ur query. $mysqli is connection object.
You can do with using a loop only
$insertQuery = 'INSERT INTO attendence (sup_payroll_type, sup_month, sup_year,
sup_late_days, sup_absent_days, sup_id, sup_emp_id,
save_edit_satt) VALUES';
foreach($attendenceArray['sup_payroll_type'] AS $key => $value){
$insertQuery .= '("'.$value.'","'.$attendenceArray['sup_month'][$key].'",
"'.$attendenceArray['sup_year'][$key].'","'.$attendenceArray['sup_late_days'][$key].'",
"'.$attendenceArray['sup_absent_days'][$key].'","'.$attendenceArray['sup_id'][$key].'",
"'.$attendenceArray['sup_emp_id'][$key].'","'.$attendenceArray['save_edit_satt'][$key].'"),';
}
echo $insertQuery; // Query for insert
i figured it out.
$ctr = 0;
foreach($_POST['sup_payroll_type'] as $row){
$upd_value = array();
$upd_value['sup_payroll_type'] = $_POST['sup_payroll_type'][$ctr];
$upd_value['sup_month'] = $_POST['sup_month'][$ctr];
$upd_value['sup_year'] = $_POST['sup_year'][$ctr];
$upd_value['sup_late_days'] = $_POST['sup_late_days'][$ctr];
$upd_value['sup_absent_days'] = $_POST['sup_absent_days'][$ctr];
$upd_value['sup_emp_id'] = $_POST['sup_emp_id'][$ctr];
$upd_result = $db_conn->mysql_update($upd_value,'tbl_attendance_support','sup_id='.$_POST['sup_id'][$ctr],'db_norkis');
$ctr++;
}
BTW thanks Pankaj K and Shijin for sharing your idea =)
Related
I have a question about my array. How can I get only data of milestone in my milestone array?
I have a query which is a prefixed array. I get data of milestones and milestonefases (this is milestone parts).
This is my code:
$stones_fases = array();
while ($row = $db->fetchassoc($result)){
$milestonefase = array();
$milestone = array();
foreach ($row as $mkey => $mvalue){
$milestone[$mkey] = $mvalue;
foreach ($row as $fkey => $fvalue){
$milestonefase[$fkey] = $fvalue;
}
}
if (!isset($stones_fases[$milestone['milestone_id']])){
$stones_fases[$milestone['milestone_id']] = $milestone; //['client']['milestone_verkocht_id']
}
$stones_fases[$milestone['milestone_id']][$milestonefase['milestonefase_id']] = $milestonefase['milestonefase_titel'];
}
I get this:
Array
(
[int] => Array
(
[milestone_id] => int
[milestone_titel] => string
[client] => string
[milestone_verkocht_id] => 99
[milestonefase_id] => 10
[milestonefase_titel] => string
[milestonefase_milestone_id] => 6
[10] => string
[11] => string
)
)
But I want this:
Array
(
[int] => Array
(
[milestone_titel] => string
[client] => string
[milestone_verkocht_id] => int
[10] => string
[11] => string
)
)
My query is this:
$project = $_COOKIE['project'];
$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`
FROM `milestones` a
INNER JOIN `milestone_parts` b ON a.id=b.milestone_id
WHERE a.verkocht_id = '{$project}' ";
$result= $db->query($dbh, $query);
I solved my own problem!
If i do this:
while ($row = $db->fetchassoc($result)){
$stones_fases[$row['milestone_id']]['milestone_titel'] = $row['milestone_titel'];
$stones_fases[$row['milestone_id']]['milestone_client'] = $row['client'];
$stones_fases[$row['milestone_id']]['milestonesfases'][$row['milestonefase_id']] = $row['milestonefase_titel'];
}
I get what i expected:
Array
(
[2] => Array
(
[milestone_titel] => Beheer opleveren
[milestone_client] => stackoverflow
[milestonesfases] => Array
(
[1] => Menu bouwen
[2] => Pagina beheer CMS
[3] => Projecten CMS
[4] => Portfolio
[5] => Footer inbouwen
)
)
)
Look at that bunch of code what I wrote a day ago.
Do you see that nonsens of code what I wrote?
Take a look at my code which I wrote 1 minute ago!
I was struggling this for 3 days and now I solved my own problem!
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
I have some data I retrieve from a JSON feed that currently is being parsed into an array like this: (simplifying for demonstration purposes)
So pretty much an array returns a movie theater name, with the showtimes associated with that particular theater.
[0] => American Theater
[1] => 2014-06-04T13:10
[2] => 2014-06-04T15:10
[3] => Grand Theater
[4] => 2014-06-04T15:30
[5] => 2014-06-04T19:10
How would I parse this array to be multidimensional, for instance:
Array
(
[0] => Array
(
[theater] => Array
(
[name] => American Theater
)
[showtimes] => Array
(
[1] => 2014-06-04T13:10
[2] => 2014-06-04T15:10
)
)
[1] => Array
(
[theater] => Array
(
[name] => Grand Theater
)
[showtimes] => Array
(
[1] => 2014-06-04T15:30
[2] => 2014-06-04T19:10
)
)
)
I'm assuming you're trying to access some api and have no control over how the data is passed back to you? If you do then the API should be responsible for returning a sensible schema.
But if you're forced to work with this array and the amount of showtimes are unknown to you, then you can do something like this:
$array = array(
'American Theater',
'2014-06-04T13:10',
'2014-06-04T15:10',
'Grand Theater',
'2014-06-04T15:30',
'2014-06-04T19:10'
);
$i = 0;
foreach ($array as $key => $value) {
if (strtotime($value)) {
$theaters[$i - 1]['showtimes'][] = $value;
}
else {
$theaters[$i]['theater']['name'] = $value;
$i++;
}
}
Outcome
To walk you through it, $array is whatever the returned dataset is. We set an index in the $i value and want to only increment it if we determine we've detected a theater name. Within the loop we first try to determine if the string can be converted to a php time value. If it cannot we add the theater name to our new schema structure, and increment our index value. Since times are always added to theater names, we are expecting the first index number to always be one higher than what we want to add the showtime to.
This will fail to be accurate in cases when a theater name is convertible to a time value in such cases like Next Month. There are a couple of other ways to solve this with regex or by inspecting the string for certain characters and their position since the time format will remain the same.
You could replace the strtotime() with:
$str = str_split($value);
if (($str[4] && $str[7]) == '-' && $str[10] == 'T' && $str[13] == ':' ) {
$theaters[$i - 1]['showtimes'][] = $value;
}
If you want such structure, you need to create a new copy of it. You may also need to chunk/group them by three's using array_chunk first, and then, from there, you can loop it now and start creating the desired format.
Consider this example:
$old_values = array('American Theater', '2014-06-04T13:10', '2014-06-04T15:10', 'Grand Theater', '2014-06-04T15:30', '2014-06-04T19:10');
$old_values = array_chunk($old_values, 3);
$new_values = array();
foreach($old_values as $key => $value) {
$new_values[] = array(
'theater' => array('name' => $value[0]),
'showtimes' => array(1 => $value[1], 2 => $value[2]),
);
}
Edit: As mentioned, one theater can have many showtimes, therefore this current solution will fail. This may be an alternative (you may need to check each element if its a theater name or a date). Consider this example:
$old_values = array(
'American Theater',
'2014-06-04T13:10',
'2014-06-04T15:10',
'Grand Theater',
'2014-06-04T15:30',
'2014-06-04T19:10',
'Magic Johnson Theater',
'2014-06-04T19:10',
'2014-06-04T19:10',
'2014-06-04T19:10',
'Mall of America Theater',
'2014-06-04T19:10',
'2014-06-04T19:10',
'2014-06-04T19:10',
'2014-06-04T19:10',
);
$new_values = array();
$current_key = 0;
foreach($old_values as $key => $value) {
$current_value = $value;
$pieces = explode('T', $current_value);
$dates = explode('-', $pieces[0]);
if(count($dates) == 3) {
$new_values[$current_key]['showtimes'][] = $current_value;
} else {
$current_key++;
$new_values[$current_key]['theater']['name'] = $current_value;
}
}
Sample Output:
Array
(
[1] => Array
(
[theater] => Array
(
[name] => American Theater
)
[showtimes] => Array
(
[0] => 2014-06-04T13:10
[1] => 2014-06-04T15:10
)
)
[2] => Array
(
[theater] => Array
(
[name] => Grand Theater
)
[showtimes] => Array
(
[0] => 2014-06-04T15:30
[1] => 2014-06-04T19:10
)
)
[3] => Array
(
[theater] => Array
(
[name] => Magic Johnson Theater
)
[showtimes] => Array
(
[0] => 2014-06-04T19:10
[1] => 2014-06-04T19:10
[2] => 2014-06-04T19:10
)
)
[4] => Array
(
[theater] => Array
(
[name] => Mall of America Theater
)
[showtimes] => Array
(
[0] => 2014-06-04T19:10
[1] => 2014-06-04T19:10
[2] => 2014-06-04T19:10
[3] => 2014-06-04T19:10
)
)
)
Sample Fiddle
i need to store the array value that are called in the class as an object in the database.
coding
<?php
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$asma[]=GA::select($ga->population,'total',3); //The best
}
print_r($asma);
?>
$array1 is the array in which i get the output value,this array is dynamic that is the number of values increases in it depend on the user input.
<?php
include('config.php');
//database connection
//query
$new_array = array($asma);
foreach($new_array as $key => $value) {
foreach ( $value as $ind => $data ) {
/*
You now have access to field values like this
$data['Voltage']
$data['Number']
$data['Duration']
*/
// query makes no sense 3 fields mentioned and 4 parameters given???
// you will have to decide which of the fields from $data[] you want to load
// to which fields in the database.
$sql = "INSERT INTO ga (gaid,fe,fe1,timestamp) VALUES ('', '$key', '$value', '".date("Y-m-d H:i:s")."')";
$stmt = mysql_query($sql) or die(mysql_error());
} // endforeach
} // endforeach
?>
if i used above code for insertion it display no error but it enter value in table ga like this
gaid fe fe1 timestamp
1 0 array -
the above code which i used for inserting in my table ga
the output of print_r($asma);
Array (
[0] => Array (
[0] => H Object (
[Voltage] => 12
[Number] => 1
[Duration] => 3
)
[1] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
[2] => H Object (
[Voltage] => 26
[Number] => 4
[Duration] => 8
)
)
[1] => Array (
[0] => H Object (
[Voltage] => 18
[Number] => 1
[Duration] => 4
)
[1] => H Object (
[Voltage] => 38
[Number] => 4
[Duration] => 10
)
[2] => H Object (
[Voltage] => 36
[Number] => 2
[Duration] => 8
)
)
)
i need to store all values in the database in above output 6 values.
this is table ga
gaid fe fe1 fe2 timestamep
It does not help that you keep talking about array1 in your description but I dont see anything called array1 in your code.
But making the assumption that array1 = $new_array here is a suggestion.
<?php
include('config.php');
//database connection
//query
/*
* This achieves nothing other than adding an extra level of array
* Try removing it
*/
//$new_array = array_combine($asma,$asma);
foreach($asma as $key => $value) {
foreach ( $value as $ind => $hObject ) {
$q = "INSERT INTO ga (fe, fe1, f2, timestamp ) VALUES (%d, %d, %d, '%s' );
$qs = sprintf( $q, $hObject->Voltage,$hObject->Duration,
$hObject->Number, date("Y-m-d H:i:s") );
$result = mysql_query($qs);
if ( ! $result ) {
die( 'Insert failed ' . mysql_errno() . ' ' . mysql_error() );
}
} // endforeach
} // endforeach
?>
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.