Insert data using multi array - php

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

Related

Find value from multidimensional array from given two values

I have the following array.
Array
(
[0] => Array
(
[product] => p1
[item] => q1
[date] => d1
[status] => N
)
[1] => Array
(
[product] => p2
[item] => q2
[date] => d2
[status] => Y
)
[2] => Array
(
[product] => p1
[item] => q3
[date] => d3
[status] => N
)
)
From this array, I want date from above with the given product and value.
For Example, I have product = p2 and item = q2 as a string. Now from this array, I want a date from this array which has product = p2 and item = q2.
So I need output from the above example is: d2
I tried array_column and array_search but can't find value from product and item both.
Please help me out with this in PHP.
You can iterate over your products and check required criteria with if statement.
foreach ($products as $product) {
if ('p2' === $product['product'] && 'q2' === $product['item']) {
var_dump($product['date']);
}
}
The conditions are as a string of type
$strCond = "product = p2 and item = q2";
given?
This is converted into an array which can be processed better:
parse_str(str_replace(' and ','&',$strCond),$cond);
/*
$cond = array (
'product_' => " p2",
'item_' => " q2",
);
*/
array_filter() with a closure which cleverly uses array_intersect_assoc() delivers the result.
$result = array_filter($input,function($row) use($cond){
return array_intersect_assoc($cond, $row) === $cond;
});
Result:
array (
1 =>
array (
'product' => "p2",
'item' => "q2",
'date' => "d2",
'status' => "Y",
),
)
As a rule, with such multidimensional arrays there are always several data records in the result. You can get the date of the first record like this:
$firstDate = reset($result)['date']; //d2
Note: The algorithm was taken from PHP class tableArray.
One way of solving with this class:
$result = tableArray::create($input)
->filterEqual($cond)
->fetchRow()
;
/*
$result = array (
'product' => "p2",
'item' => "q2",
'date' => "d2",
'status' => "Y",
)
*/

Specific value in an array does not work

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!

Parsing array values into multidimensional array

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

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

How to copy single array from multidimensional array?

I have one multidimensional array as shown below(PHP) :
Array
(
[144320] => Array
(
[3568728] => Array
(
[30832] => 30832
)
[3568884] => Array
(
[30827] => 30827
[30828] => 30828
[30830] => 30830
[30831] => 30831
[30832] => 30832
[30837] => 30837
[30838] => 30838
[30839] => 30839
[30826] => 30826
[30808] => 30808
[30806] => 30806
[30807] => 30807
[30698] => 30698
[30601] => 30601
[30697] => 30697
)
)
[144330] => Array
(
[3568731] => Array
(
[30827] => 30827
[30839] => 30839
[30838] => 30838
[30837] => 30837
[30832] => 30832
[30831] => 30831
[30828] => 30828
[30830] => 30830
[30826] => 30826
[30806] => 30806
[30808] => 30808
[30807] => 30807
[30698] => 30698
[30697] => 30697
[30601] => 30601
)
)
[144218] => Array
(
[3568753] => Array
(
[30808] => 30808
)
)
[144216] => Array
(
[3568732] => Array
(
[30808] => 30808
)
)
)
This array is populated by following code:
$sql = "SELECT * FROM `bf_alert_stack` WHERE `type` = 'immediately' order by created desc";
$q = db_query($sql);
$user_alerts = array();
while ($row = db_fetch_array($q))
{
$user_alerts [$row['uid']] [$row['alert_id']] [$row['nid']] = $row['nid'];
}
From the above user_alerts array I want to rearrange the [$row['nid']] array and for rearrangement I want capture [$row['nid']] array and after capturing it into another array I want to re-arrange $row['nid'] array I want to update this $row['nid'] array into original user_alerts array.
How I can do this? I am not getting any search for this on google so just placed this on appropriate place.
The best you can do is to get it ordered from the query with something like:
SELECT * FROM `bf_alert_stack` WHERE `type` = 'immediately'
ORDER BY created desc, nid
But if you don't have access, or need the original sort for other reason, you need to iterate recursively over the array and reassign the last sortered level to the original array with PHP ksort method:
http://www.php.net/manual/en/function.ksort.php
foreach($user_alerts as $uid=>$user_alert) {
foreach($alert as $alert_id=>$nids) {
$user_alerts[$uid][$alert_id] = ksort($nids);
}
}
Hope it helps!

Categories