I am trying to insert multiple raw into database on plugin activation, and I manage to insert only one raw.
I can figure out how to add multiple raw for example 10 raw.
Below is the working code that is inserting one raw only:
function my_func() {
global $wpdb;
$_IL_TABLE_SETTINGS = $wpdb->prefix . "table";
$wpdb->insert(
$_IL_TABLE_SETTINGS,
array( 'id' => '1', 'options' => 'something', 'values' => 'something' ));
}
I tried like this but is not working for the second raw:
function my_func() {
global $wpdb;
$_IL_TABLE_SETTINGS = $wpdb->prefix . "table";
$wpdb->insert(
$_IL_TABLE_SETTINGS,
array( 'id' => '1', 'options' => 'something', 'values' => 'something' ),
array( 'id' => '2', 'options' => 'something', 'values' => 'something' )
);
}
How i can add this values into your code:
$id = array('1', '2', '3');
$op = array('first', 'second', 'thaird');
$data = array('value1', 'value2', 'value3');
I will appreciate any help.
Here is the code which will work.
$id = array('1', '2', '3');
$op = array('first', 'second', 'thaird');
$data = array('value1', 'value2', 'value3');
for($i=0;$i<count($id);$i++)
{
$wpdb->insert($_IL_TABLE_SETTINGS,array("id"=>$id[$i],"option"=>$op[$i],"values"=>$data[$i]));
}
Please let me know if it didnt work for you.
for example if you want to add 10 records then you can try for loop:
for($i=0;$i<10;$i++)
{
$wpdb->insert(
$_IL_TABLE_SETTINGS,
array( 'id' => '$i', 'options' => 'something', 'values' => 'something' ),
}
of course you will need to add your dynamic data accordingly.
You can add a loop into it and put the $wpdb->insert inside that loop.
If value is stored in an array
$arr=array();//containing the values you want to insert
$arr[0]=array("id"=>idvalue,"key"=>"value");
for($i=0;$i<count($arr);$i++)
{
$wpdb->insert($_IL_TABLE_SETTINGS,$arr[$i]));
}
if you want to store imaginari values
for($i=0;$i<count($arr);$i++)
{
$wpdb->insert($_IL_TABLE_SETTINGS,array( 'id' => $i, 'options' => 'something', 'values' => 'something' ));
}
Hope you can relate your code with the above one, if no please let me know.
Related
first of, just wanted to let you know that I am a newbie at CI. but I am having trouble with this piece of code where is breaking and I can't seem to be able to find the answer anywhere.
for some reason the code is breaking at the first if statement.. if possible could you help me out understand what is really happening there?
Thank you all for your help!
function main
{
$this->load->model(getData) psudo code for this area...
}
---model---
function getData....
{
Sql = this->db->query(sql code that returns all the information required.)
$result = $sql->result_array();
$types = array ( 'EVENT|TIME' => array( 'id' => 1, 'name' => 'Regular' ),
'PROPOSITION|REGULAR' => array( 'id' => 2, 'name' =>'Propositions'),
'EVENT|TIME' => array( 'id' => 3, 'name' => 'Now' ),
'PROPOSITION|FUTURES' => array( 'id' => 4, 'name' => 'Future' ));
$var = array();
foreach ($result as $event) {
$cat = $event['type'] . '|' . $event['sub_type'];
$typeId = $types[$cat]['id'];
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
{
if(!is_array($var[$event['event_id']]))
{
$var[$event['event_id']] = array( 'event_name' =>
$event['event_name'],'event_abbreviation' =>
$event['event_abbreviation']);
}
$var[$event['event_id']]['var'][$event['type_id']] = array(
'type_name' => $event['abbreviation'],'type_abbreviation' => $event['name']
);
}
$event[$event['event_id']]['var'][$event['type_id']]['types'][$typeId] =
$types[$cat]['name'];
}
return $myResults;
}
In this line
if(!is_array($var[$event['event_id']]['var']$event['type_id']]))
You are missing a [ somewhere. I'm guessing before $event['type_id'].
So replace with:
if(!is_array($var[$event['event_id']]['var'][$event['type_id']]))
I have an array that looks like the following:
Data = array(
'Offer' => array(),
'Country' = array('Name' => Array())
)
Now if i want to sort on the value of the first item of the Name array how would i go around that?
Ive tried this so far:
$dataArray = $originalData['data'];
$dataArray = Set::sort($dataArray, '{n}.Country.Name', $direction);
However this did not work
Note im using CakePHP set::Sort is a part of Cakephp
Okay seems i wasnt clear enough so here is a more detailed explaination of my problem:
So ive created my own datasource in cake that collects data from an API.
The API returns data in a way that looks like this:
data = array(
'Offer' => array('id' => 2, 'name' = 'ExampleName'),
'Stat' => array('Stat1' = 1, 'Stat2' = 2),
'Country => array('Name' => array('name1','name2')
);
Now in order to make the user able to sort these data i have to make sure that i display correctly.
This works fine when there is only one value i.e:
$dataArray = $originalData['data'];
$dataArray = Set::sort($dataArray, '{n}.Stat.Stat1', 'ASC);
$originalData['data'] = $dataArray;
However country is an array so in order to "copy" the code above i need to use the first item of the Country['Name'] array.
to do something like this:
$dataArray = $originalData['data'];
$dataArray = Set::sort($dataArray, '{n}.Country.Name', $direction);
$originalData['data'] = $dataArray;
However the above code is failing ...
created test data:
$dataArray = array();
$data = array(
'Offer' => array('id' => 2, 'name' => 'ExampleName'),
'Stat' => array('Stat1' => 1, 'Stat2' => 2),
'Country' => array('Name' => array('z','name2'))
);
array_push($dataArray,$data);
$data = array(
'Offer' => array('id' => 2, 'name' => 'ExampleName'),
'Stat' => array('Stat1' => 1, 'Stat2' => 3),
'Country' => array('Name' => array('a','name2'))
);
array_push($dataArray,$data);
print_r(Set::sort($dataArray,'{n}.Country.Name','asc'));
Link with output array:https://gist.github.com/anonymous/6462971
My initial array is
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
I am trying to create a new array based on the search results of another array so the new array should look like this if I search for 'crafts':
$employees2 = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'brad',
'area' => 'crafts')
);
What is the simplest solution I can do get get this new result.
foreach($employees as $key => $value){
if($value['area']=='crafts'){
$employees2[] = $value;
}
}
This quite simply loops through the first array and checks the value of "area" in the internal array. If the value is equal to "crafts" you can then put that into a new array which is called $employees2. You can change crafts to whatever you want and add anything you want between the [ ] in employees2 if you wish to customise the key.
Try this:
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees2 = array();
foreach ($employees as $key) {
if($key['name'] == "jack")
{
array_push($employees2,array('name'=>$key['name'],'area'=>$key['area']));
}
}
var_dump($employees2);
The array_push do all the trick ;)
Saludos.
You could simplify the syntax (but not the algorythmic complexity) by using a utility-belt library Underscore.php (http://brianhaveri.github.com/Underscore.php/)
There's a number of array-"plucking" methods that saves you the need to write loops, but under the bonnet it does much of the same as decribed in answers above.
I will assume that the possible result set can be large. In which case you would want to process the array with as little extra memory as possible. For this I suggest iterating through the array by reference and unsetting the items that do not match your criteria. Possibly less overhead than creating a new array to store the items that match your filter. Then you can check if the array is empty or not to determine if the filter returns any results. Like so:
<?php
// maybe this will be set through an option from the UI
$area_filter = 'crafts';
// fetched results
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
// filter out the items that match your filter
foreach($employees as $i => &$employee){
if($employee['area'] != $area_filter){
unset($employees[$i]);
}
}
// do something with the results
if(!empty($employees)){
print_r($employees);
} else {
echo "Sorry, your filter '$area_filter' did not match any results\n";
}
?>
Try this :
$employees = array(
array('name' => 'jack',
'area' => 'crafts'),
array('name' => 'janet',
'area' => 'aquatics'),
array('name' => 'brad',
'area' => 'crafts')
);
$employees = array_filter($employees, function($employee) {
return ($employee['area'] == 'crafts' );
});
echo "<pre>";
print_r($employees);
So I'm new to Arrays, but I think this should be fairly easy, I just can't wrap my head around it.
I've got an array, that can have a varying amount of keys in it, based on how much input is given by the user.
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10'
));
easy enough, right?
but I've got 1-4 more keys that could be in it, based on user input. They fill out a form on the first page, and it submits to the second page (which contains the array above).
I need to grab City, State, First, last, based on how many fields the user fills out on the previous page. I can't have blank ones so
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
'city' => '',
'state' => '',
'first' => $_GET['first']
));
won't really work. I need a way to determine which fields have been submitted (preferrably via GET) and build the array that way. so can end up with
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
'state' => $_GET['state'],
'first' => $_GET['first']
));
because state and first had a value while city and last did not.
The first thing that came to mind was something like
$array = MY_Class( array(
'type' => 'representatives',
'show_this_many' => '10',
$constants => $variables
));
//where
$constants = array( //_GET stuff values );
$variables = array( //_GET stuff with values );
// magic method to make it like
// CONSTANTS[0] => VARIABLES[0];
// CONSTANTS[1] => VARIABLES[1];
// so everything is lined up
but I'm not sure how to do it :/
You will want to use a whitelist of possible keys from $_GET so your array doesn't get polluted with spurious (or possibly malicious) keys, and then you can simply append them onto your array with a loop over $_GET.
// Your array is already initialized with some values:
$array = array(
'type' => 'representatives',
'show_this_many' => '10'
);
// Allowed GET keys
$allowed = array('city','state','first');
// Loop over get and add the keys (if allowed)
foreach ($_GET as $key => $value) {
// If the key is allowed and the value isn't blank...
if (in_array($allowed, $key) && !empty($value)) {
$array[$key] = $value;
}
}
// See all the newly added keys...
var_dump($array);
Another option is to just add all the keys to the array, then call array_filter() to remove the blanks.
$array = array(
'type' => 'representatives',
'show_this_many' => '10',
'city' => '',
'state' => '',
'first' => ''
);
// Add values from $_GET, then filter it
$array = array_filter($array, function($val) {
return $val !== '' && !is_null($val);
});
Try the below code
$array = array(
'type' => 'representatives',
'show_this_many' => '10'
);
$fields = array ('city', 'state', 'first');
foreach ($fields as $field) {
if (!empty($_GET[$field])) {
$array[$field] = $_GET[$field]
}
}
Official PHP documentation states that filter_var_array() supports array filtering in the following format:
$data = array(
'testarray' => array('2', '23', '10', '12')
);
$args = array(
'testarray' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY
)
);
$myinputs = filter_var_array($data, $args);
However, if the array in question is multi-dimensional and requires different filters for different parts, how would you approach defining filtering options?
As an example:
$data = array(
'testhash' => array('level1'=>'email',
'level2'=> array('23', '10', '12'))
);
Idea 1
Consider using FILTER_CALLBACK. In this way, you can write a callback function that itself uses the filter extension, thus providing a recursive ability.
function validate_array($args) {
return function ($data) use ($args) {
return filter_input_array($data, $args);
};
}
This will generate the callback functions.
$args = array(
'user' => array(
'filter' => FILTER_CALLBACK,
'options' => validate_array(array(
'age' => array('filter' => FILTER_INPUT_INT),
'email' => array('filter' => FILTER_INPUT_EMAIL)
))
)
);
This is what the config array would then look like.
Idea 2
Do not hesitate to pat me on the back for this one because I am quite proud of it.
Take an arg array that looks like this. Slashes indicate depth.
$args = array(
'user/age' => array('filter' => FILTER_INPUT_INT),
'user/email' => array('filter' => FILTER_INPUT_EMAIL),
'user/parent/age' => array('filter' => FILTER_INPUT_INT),
'foo' => array('filter' => FILTER_INPUT_INT)
);
Assume your data looks something like this.
$data = array(
'user' => array(
'age' => 15,
'email' => 'foo#gmail.com',
'parent' => array(
'age' => 38
)
),
'foo' => 5
);
Then, you can generate an array of references that map keys such as 'user/age' to $data['user']['age']. In final production, you get something like this:
function my_filter_array($data, $args) {
$ref_map = array();
foreach ($args as $key => $a) {
$parts = explode('/', $key);
$ref =& $data;
foreach ($parts as $p) $ref =& $ref[$p];
$ref_map[$key] =& $ref;
}
return filter_var_array($ref_map, $args);
}
var_dump(my_filter_array($data, $args));
Now the only question is how you deal with the mismatch between the validation record and the original data set. This I cannot answer without knowing how you need to use them.