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);
?>
Related
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 =)
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
The scenario is
Original source is look like (it is without the attribute email , name....etc):
a#a.com leo
foodil#g.com NULL
I would like to insert an record like this:
Firstly, i have an array of what datafield i need to insert
$field = Array ( [0] => Email [1] => Name )
Secondly, I have an array of mail
$mail = Array ( [0] => a#a.com [1] => foodil#g.com )
=============================================================================
Lastly, I have an multi dimension array that has datafield e.g. Name,
$set = Array ( [1] => Array ( [1] => leo [4] => NULL ) )
however, It can be more than one field,
eg. it can be also have a field of phone (and also address, geneder...whatever) , then it will be:
It is random index because the counting skip the mail column
eg.
leo a#a.com 4343343
NULL foodil#g.com 3453343
$field = Array ( [0] => Email [1] => Name [2] => Phone )
$set = Array ( [0] => Array ( [1] => leo [4] => NULL ) [2] => Array ( [1] => 4343343 [4] => 3453343 ))
=============================================================================
The problem is , how to insert in the scenario like this? :
The query should look like this
And the mail will be tested, only if it is true, then insert.
eg. a#a.com is invalid, then i have to skip leo and 4343343
$query="INSERT INTO subscriber (Email,Name,Phone) VALUES ($mail[] , $set[][], $set[][])";
Use this it will give 2D array.
After getting array make foreach loop & insert into database.
$field = array ( '0' => 'Email', '1' => 'Name', '2' =>'Phone' ) ;
$mail = array ( '0' => 'a#a.com', '1' => 'foodil#g.com' );
$set = array ( '0' => array ( '1' => 'leo', '4' => NULL ), '2' => array ( '1' => '4343343', '4' => '3453343' )) ;
$res = array();
$key1= array_keys($mail);
foreach($key1 as $a=>$key){
if(array_key_exists($key, $set)){
$res[$a]['Email'] =$mail[$key];
$res[$a]['Name'] = $set[$key]['1'];
$res[$a]['Phone'] = $set[$key]['4'];
unset($set[$key]);
}else{
$res[$a]['Email'] =$mail[$key];
$res[$a]['Name'] = '';
$res[$a]['Phone'] = '';
}
}
$total = count($res);
foreach($set as $q){
$res[$total]['Email'] ='';
$res[$total]['Name'] = $q[1];
$res[$total]['Phone'] = $q[4];
$total++;
}
I have an sql query which outputs an array the output looks like this
Array
(
[0] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 13
[name] => QUESTION_HEADLINE
[value] => Bitte geben Sie Ihren Downloadkey ein:
)
[1] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 15
[name] => QUESTION_BUTTON
[value] => Start!
)
[2] => Array
(
[customer_id] => 7
[language_id] => 1
[variableitem_id] => 6
[name] => PAGETITLE
[value] => Steigenberger Hotels and Resorts - Mediathek
)
)
In my controller I get it as
$data['variables_data'] = $this->Home_model->getVariables($customer_id, $language_id);
Now for different ids in the url like for
localhost/home/user/12 and localhost/home/user/14
the positions of the variable differs
for example in my view when I echo
$variable[0]['value']
it gives QUESTION_HEADLINE for one user and PAGE_TITLE for the other .
Is it possible to make them same for all of the user like if I echo
$variable[0]['value']
it should return me QUESTION_HEADLINE every time and for every user
Code for Home model get_variables function
function getVariables($customer_id, $language_id) {
$query = $this->db->query("SELECT customers_idcustomers AS customer_id,
languages_idlanguages AS language_id,
variableitems_idvariableitems AS variableitem_id,
variableitem AS name,
variabletext AS value
FROM variables v
LEFT JOIN variableitems vi ON v.variableitems_idvariableitems = vi.idvariableitems
WHERE v.customers_idcustomers ='" . $customer_id . "'
AND v.languages_idlanguages =" . $language_id
);
$var = $query->result_array();
return $var;
}
Thanks in advance
You can set it explicitly, like
foreach($outArray as $output)
{
$output['name']="Any thing you want";
}
So , as i understand you want to make reduce your output to one dimension. It can be done with MYSQL also. Here php version:
In your controller
$data = $this->Home_model->getVariables($customer_id, $language_id);
$data['variables'] = array(
'customer_id' => $data[0]['customer_id'],
'language_id' => $data[0]['language_id'],
'variableitem_id' => array(),
'name' => array(),
'value' => array()
);
foreach($data as $k => $v) {
$data['variables']['variableitem_id'][] = $v['variableitem_id'];
$data['variables']['name'][] = $v['name'];
$data['variables']['value'][] = $v['value'];
}
And in your view
echo $variables['value'][2].' '.$variables['value'][3];
//do whatever you want
I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.