i have the requirement, when user checks checkbox, i m getting checkbox value as key value pair
Array(
[checkboxname] => Array(
[1] => on
[5] => on
[12] => on
[15] => on
)
)
i have to pass this key in sql statement and retrive another checkbox from this key.
this is query i have to write
foreach($array as $key => $value)
{
}
$reult = $this->db->get_where('select_another_value ', array('id' => $key))->result_array();
what should i write in query instead of $key
Suppose you want to get all checked check boxes value from db, and Id inside array key and use where_in() method and pass array keys in array, see below sample code
$all_keys = array_keys($arr['checkboxname']);
$result = $this->db->where_in('id', $all_keys)
->get('select_another_value')->result_array();
Try with -
foreach($array as $key => $value){
$reult[] = $this->db->get_where('select_another_value ', array('id' => $key))->result_array();
}
Or you can try with -
$keys = array();
foreach($array as $key => $value){
$keys[] = $key;
}
if (count($keys) > 1) {
$where = " id IN (".implode(',', $keys).")";
} else {
$where = " id = '".$key[0]."'";
}
$this->db->where($where);
If you want to avoid running query inside loop.
Related
Hello guys, and Happy new year!
How can I add keys to this array
$my_array = array( [0] => 703683 [1] => 734972 [2] => 967385 )
So I would like to add a single key to all values example:
$copy_array = array( ['id'] => 703683 ['id'] => 734972 ['id'] => 967385 )
I tried this solution:
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr['id'] = $value ;
}
Output:
( [id] => 703683 )
You can't. An array key is identifying the element it represents. If you set 'id' to be a specific value, then you set it to be another specific value, then you override the former with the latter. Having separate values as ids is self-contradictory anyway, unless they identify different objects. If that's the case, then you can change your code to
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[] = ['id' => $value] ;
}
or even
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[$value] = ['id' => $value] ;
}
but the only use of such a change would be if they have other attributes, which are not included in the codes above, since your question does not provide any specific information about them if they exist at all. If everything is only an id, then you might as well leave it with numeric indexes.
I have a table on the frontend, where the user can choose what types of columns he wants.
After submitting the form I get the array with selected columns.
For instance the user select following columns:
$columns = ["campaign_start_time", "campiagn_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"]
Now I have to make the request to the facebook api, but facebook api only request query in form:
$query = "campaign{start_time, end_time, id, budget}, adset{name}, ad{name}"
Here is my question, what is the best way to convert $columns to $query in PHP language?
If you can construct your submitted data to be in this form:
Array
(
[campaign] => Array
(
[0] => start_time
[1] => end_time
[2] => id
[3] => budget
)
[adset] => Array
(
[0] => name
)
[ad] => Array
(
[0] => name
)
)
Maybe using inputs or other constructs such as:
name="campaign[]" value="start_time"
name="campaign[]" value="end_time"
Then looping and building the query with the keys and values will do it:
foreach($columns as $key => $val) {
$query[] = $key . '{' . implode(',', $val) . '}';
}
$query = implode(',', $query);
Otherwise you'll need to parse it to get what you need first, then execute the loop above using $result instead:
foreach($columns as $val) {
preg_match('/^([^_]+)_(.*)/', $val, $match);
$result[$match[1]][] = $match[2];
}
This solution splits apart the values based on underscores and then joins them back together as nested values based on the category/key. Note that this doesn't check for items that don't have a "prefix".
<?php
$columns = ["campaign_start_time", "campaign_end_time", "campaign_id", "campaign_budget", "adset_name", "ad_name"];
$criteria = [];
foreach( $columns as $column ){
$pieces = explode('_',$column);
$category = array_shift($pieces);
if( !isset($criteria[$category]) ){
$criteria[$category] = [];
}
$criteria[$category][] = implode('_', $pieces);
}
$queryPieces = [];
foreach($criteria as $category => $values){
$queryPieces[] = $category.'{'.implode(', ', $values).'}';
}
$query = implode(', ', $queryPieces);
I have a multi dimensional array that I have got from a database and I want to check this array for duplicate data and store it in another array of duplicates. my code is as follows
//create temp array
$tmp = array();
foreach ($matchingarray as $nameKey => $match) {
// loop through and stoe the contents of that array to another so i can compare
$tmp[] = $match;
}
// create an array to store duplicates
$duplicatesArray = array();
// if the temp array is not empty then loop through both arrays
if (! empty($tmp)) {
foreach ($tmp as $key => $tmpvalue) {
foreach ($matchingarray as $key => $match) {
// if a key name is the same in both arrays then add it tothe duplicates array
if ($tmpvalue['name'] == $match['name']) {
$duplicatesArray = $match;
}
}
}
}
//count how many are duplicates
$dups = count($duplicatesArray);
What I would like to know is this the right logic?
I will take where Igoel left off
there is 1 error and also 1 suggest that i will make.
Error:
you cannot reuse $key twice in the foreach because they will override.
Suggestion as what Igoel stated: your best bet for duplicate effectively is to use sql. SQL is faster at processing than looping through arrays. Don't forget you need to load the data into memory and thats costly.
Try this way
<?php
static $cnt = array();
$min = 1;
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k){
global $cnt;
$cnt[] = $v;
}
array_walk_recursive($coll, 'recursive_search');
$newNumbers = array_filter(
array_count_values($cnt),
function ($value) use($min) {
return ($value > $min);
}
);
echo "Values > 1 are repeated \n";
print_r(array_count_values($cnt));
echo "Values repeted\n";
print_r($newNumbers);
DEMO
I have a check box which takes some values and the below one is the post value which I get from my matrix form. Now the array value which I have below should be formated as like this
Post values:
Array (
[31_1] => on
[31_2] => on
[31_3] => on
[56_2] => on
[56_4] => on
[66_1] => on
[66_3] => on
)
Expected value:
31=>1,2,3
56=>2,4
66=>1,3
I will be happy if I am able to store the values in a database table (author_book) like this:
S.No Author_ID Book_IDs
1 31 1,2,3
2 56 2,4
3 66 1,3
In short, the post values should be stored in DB tables for me to proceed further. How can I achieve this?
This code would construct the queries for you, remember to use some data injection prevention mechanism
<?php
$x = array (
"31_1" => "on",
"31_2" => "on",
"31_3" => "on",
"56_2" => "on",
"56_4" => "on",
"66_1" => "on",
"66_3" => "on"
);
$newarray = array();
foreach($x as $key => $val){
$key = explode("_", $key);
$newkey = $key[0];
$newval = $key[1];
$newarray[$newkey][] = $newval;
}
foreach($newarray as $key => $val){
$query = "INSERT INTO (Author_ID, Book_IDs) VALUES (" . $key . ",'" . join(',', $val) . "')";
echo $query . "<br />";
}
foreach($array_name as $key=> $value)
{
$var1=$key;
$var2=$value;
// here you can have your db statements to insert the values
}
Here you go. There might be a shorter way of doing it too:
<?php
$array = array (
'31_1' => 'on',
'31_2' => 'on',
'31_3' => 'on',
'56_2' => 'on',
'56_4' => 'on',
'66_1' => 'on',
'66_3' => 'on',
);
$new_array = array();
foreach($array as $ind=>$val){
//breaks string at '_' and gets 31 and 1 separately
$key_val = explode('_',$ind);
if(array_key_exists($key_val[0],$new_array)){
//this is to append if key exists, eg. 31 => 1,2,3
$new_array[$key_val[0]] = $new_array[$key_val[0]].",".$key_val[1];
}
else
{
$val = $key_val[1];
$new_array[$key_val[0]] = $val;
}
}
print_r($new_array);
?>
Fiddle
I believe you only wanted to insert values for author_id whose is set to ON
unset all the index set to OFF
Try something similar:
$books=array();
foreach($array_name as $key=> $value){
if($value==='on'){
//prepare the array
list($author_id,$books[$author_id][])=explode("_",$key)
}
}
foreach($temp as $k=>$v){
$q->query("INSERT INTO author_book(author_id,books_id) VALUES($k,".implode(',',$v)));
}
Thanks
and keep asking questions :)
In my program I send an SQL query to a table and it returns a resource which I use the function mysql_fetch_array() on. The first argument is the results resource from the SQL query but if you leave the next argument out the default is to return an array which has both the associative index id and the numerical id.
This is useful to me because I'm using these results to create another query so need to have access to both the associative id and the numerical one since I need to iterate through this array which involves incrementing the number. However, I have removed the null values through a PHP function and now I am left with an discontinuous numerical entries. I understand that I can use the array_values() function to recalibrate my IDs but this eliminates my associative IDs from the array.
Is there a way to only recalibrate my numerical ID's but not remove the associative ID?
e.g.
'id' = [0] = '0001'
'gender' = [1] = null
'religion' = [2] = 'jewish'
I removed the null values, i.e. gender:
'id' = [0] = '0001'
'religion' = [2] = 'jewish'
Now I want to renormalise the numerical indices to:
'id' = [0] = '0001'
'religion' = [1] = 'jewish'
I don't think there's a built in function for this, however you can iterate trough the array to get the numerically indexed values:
$data = array(
'id' => '0001',
'gender' => null,
'religion' => 'jewish',
0 => '0001',
1 => null,
2 => 'jewish',
);
$num_keys = array();
foreach ($data as $k => $v) {
if ($v === null) {
unset($data[$k]);
continue;
}
if (is_numeric($k)) {
$num_keys[$k] = $v;
unset($data[$k]);
}
}
ksort($num_keys);
$data = array_merge($data, array_values($num_keys));
var_dump($data);
I didn't verified this but I think this should work. If not tell me and I'll delete my answer.
$i=0;
foreach($array as $key=>$value) {
$array2[$i] = $array2[$key] = $value;
$i++;
}