Looping through array of array/objects - php

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.

Related

PHP - Array does not turn into two-dimensional array

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

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

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.

multiple form insert query mysql

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

Why the value of first element only is getting displayed?

I'm having two arrays i'm inserting one array into another. This operation is done for each element of first array using foreach loop. But I'm able to attach only first pair of key value pairs to the first array during second iteration it does not. Can you help me in achieving this for aal array elements? My code is as follows:
$data = $grid->GetData();
//print_d($data);
foreach($data as $key => $value) {
$sql =" SELECT users_details.user_state, users_details.user_city FROM ".TBL_USERS." AS user JOIN ";
$sql .= TBL_USERS_DETAILS." AS users_details on user.user_id = users_details.user_id ";
$sql .=" WHERE user.user_id = '". $value['user_id']."'" ;
$gDb->Query( $sql );
$user_data = $gDb->FetchArray(MYSQL_FETCH_SINGLE);
$data[$key]['user_state'] = $user_data['user_state'];
$data[$key]['user_city'] = $user_data['user_city'];
}
The first array named $data is as follows:
Array
(
[0] => Array
(
[user_id] => 9def02e6337b888d6dbe5617a172c18d
[user_first_name] => Ashutosh
[user_last_name] => Modi
[user_email] => ashutosh.modi#gmail.com
[user_status] => enable
[user_subscription] => lifetime
[user_registered_type] => online
[user_reg_date] => 1325581397
)
[1] => Array
(
[user_id] => a6d22e4cc3f65778a60b359842bcec82
[user_first_name] => Dilip
[user_last_name] => Modi
[user_email] => dm.modi#gmail.com
[user_status] => enable
[user_subscription] => period
[user_registered_type] => online
[user_reg_date] => 1325152066
)
)
The first iteration of second array named $user_data is as follows:
Array
(
[user_state] => Rajasthan
[user_city] => Jhunjhunu
)
Now after attaching this the array $data becomes as follows:
Array
(
[0] => Array
(
[user_id] => 9def02e6337b888d6dbe5617a172c18d
[user_first_name] => Ashutosh
[user_last_name] => Modi
[user_email] => ashutosh.modi#gmail.com
[user_status] => enable
[user_subscription] => lifetime
[user_registered_type] => online
[user_reg_date] => 1325581397
[user_state] => Rajasthan
[user_city] => Jhunjhunu
)
[1] => Array
(
[user_id] => a6d22e4cc3f65778a60b359842bcec82
[user_first_name] => Dilip
[user_last_name] => Modi
[user_email] => dm.modi#gmail.com
[user_status] => enable
[user_subscription] => period
[user_registered_type] => online
[user_reg_date] => 1325152066
[user_state] =>
[user_city] =>
)
)
I'm not getting why the second array is having the blank values for user_state and user-city. Even after having the values of the array $user_data in second iterations are as follows:
Array
(
[user_state] => Arunachal Pradesh
[user_city] => Shollong
)
Can you resolve my this issue. Thanks in advance.
user_state and user_city are both added, so your code is working fine. You gotta know why $user_data is empty there.
Make your code like this:
echo $sql;
print_r($user_data);
$data[$key]['user_state'] = $user_data['user_state'];
$data[$key]['user_city'] = $user_data['user_city'];
That will output your sql for each loop and print_r function (or var_dump) will echo $user_data array right before those lines. Check why it is empty. Probably your second query in that loop is not what you think it is.
Your insertion is lie inside array of array. Try this
$i=0;
foreach($data as $key => $value) {
$sql =" SELECT users_details.user_state, users_details.user_city FROM ".TBL_USERS." AS user JOIN ";
$sql .= TBL_USERS_DETAILS." AS users_details on user.user_id = users_details.user_id ";
$sql .=" WHERE user.user_id = '". $value['user_id']."'" ;
$gDb->Query( $sql );
$user_data = $gDb->FetchArray(MYSQL_FETCH_SINGLE);
$data[$i]['user_state'] = $user_data['user_state'];
$data[$i]['user_city'] = $user_data['user_city'];
$i++;
where $i represent the array key inside your data file which is default indexing start from 0 & go to 1,2 & so on in your data file..
Also Explore the following program may be find any thing good & being helpful in form to sort out your problem.
e.g a program to update the array inside array.
<?php
$d3 = array('0'=>array('b'=>'1','c'=>'2'),'1'=>array('b'=>'3','c'=>'4'));
$i=0;
foreach($d3 as $k => $v){
$d3[$i]['b'] = "h";
$i++;
}
print_r($d3);
?>

Categories