I have an array like this:
$where = array(
'product_id' => $product_id,
'item_id' => $item_id
);
I want to add to this array, based on a condition, so I could do
if($condition){
$where = array()
}else{
$where = array()
}
And repeat the original contents twice, but ideally, I'd like to do like an array_push(array('id' => $id), $where);
Thanks!
you may add something to your array in the following way:
$where['mykey'] ='myvalue';
Simply add it to your array by specifying the index and the value.
if($condition){
$where['id'] = $id;
}else{
$where['other'] = $other;
}
Related
I want to call the method $wpdb->get_results(),
and I need to add parameters (WHERE clauses) to the SQL query.
The thing is, I want to build a generic function that will receive a parameters object and will generate an SQL query which includes my parameters.
So, for example, if this is my base query:
$taxis = $wpdb->get_results("SELECT * FROM $table", ARRAY_A); // base query
And these are my parameters:
$params = array(
'color' => 'blue',
'model' => 'ford'
);
It will call get_results with the following query:
SELECT * FROM $table WHERE color='blue' AND model='ford';
Is there a way to build a function that will have this behaviour?
*NOTES:
I don't know how many parameters are going to be in the parameters object nor which parameters they will be (that is why it has to be generic).
I do know, (in my case) that the only SQL CLAUSES I am going to need are WHERE =.
See the code comments for an explanation on what is happening in each step:
<?php
// make sure this doesn't come from user input, as it is inserted into the query directly
$tableName = $wpdb->prefix . "yourtable";
$columnWhitelist = array( 'color', 'model' );
$params = array(
'color' => 'blue',
'model' => 'ford'
);
// filter param keys by allowed column names defined in $columnWhitelist
$params = array_filter(
$params,
function ( $key ) use ( $columnWhitelist ) {
return in_array( $key, $columnWhitelist );
},
ARRAY_FILTER_USE_KEY
);
$whereClauseParts = array();
// put column/value pairs of $params into $placeholderValues array
$placeholderValues = array();
foreach ( $params as $column => $value) {
$whereClauseParts[] = "`$column` = %s";
$placeholderValues[] = $value;
}
// put together the WHERE clause with placeholders
$whereClause = implode(' AND ', $whereClauseParts );
// put together the whole query tring
$queryString = "SELECT * FROM `$tableName` WHERE " . $whereClause;
// you can use this to see what your prepared query will roughly look like,
// but with missing single quotes around the values
// die( vsprintf(
// $queryString,
// $placeholderValues
// ) );
$wpdb->get_results(
$wpdb->prepare(
$queryString,
$placeholderValues
)
);
I have a array that looks like this:
[['title'= >'my title','time'=>'14:00','date'=>'feb 2'],['title'= >'another','time'=>'14:00','date'=>'feb 2']]
Now I wish to remove all time and date keys from the arrays and also rename the title to text so it looks like this:
[['text'= >'my title'],['text'= >'another title']]
I have tried to use
$tags = array_map(function($tag) {
return array(
'text' => $tag['title'],
);
}, $tags);
But I cant get it to work
Laravel solution:
collect($array)->transform(function($i) { return ['text' => $i['title']]; })->toArray();
You can transform your collections,
$mycollection = $myModel->get();
return $mycollection->map(function($row){
return [
'text' => $row->title,
];
});
Or you can use Fractal: http://fractal.thephpleague.com/transformers/
$newTags = [];
foreach($tags as $tag) {
$newTags[] = [['text'] => $tag['title']];
}
$tags = $newTags;
This question isn't specific to Laravel, but since you mention it:
Use the collect() helper and it's methods for convenience. You'll want to look at pull, map, and maybe transform in particular.
If you don't use it then unset will delete the index you want from the array.
Alternatively, just create a new array:
$a = []
foreach($tags as $tag) {
$a[] = ['text' => $tag['title']];
}
edit: fix
Say I have an array like this
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
How can I remove the first dimensional element if one of its 'post_title' or 'post_id' value is repeated?
Example:
Suppose we know that 'post_title' is '10' in two first dimensional elements.
How can I remove the repeated element from $posts?
Thanks.
Create a new array where you will store these post_title values. loop through $posts array and unset any duplicates. Example:
$posts = array(
array('post_title'=>10, 'post_id'=>1),
array('post_title'=>11, 'post_id'=>2),
array('post_title'=>12, 'post_id'=>3),
array('post_title'=>13, 'post_id'=>4),
array('post_title'=>10, 'post_id'=>5)
);
$tmp_array = array();
foreach ($posts as $i => $post)
{
if (!in_array($post['post_title'], $tmp_array)) // if it doesn't exist, store it
{
$tmp_array[] = $post['post_title'];
} else { // element exists, delete it
unset($posts[$i]);
}
}
Now in your $posts array you will have unique post_title values.
This is the first time i create my own webservice (someone always did it for me before), so please bear with me.
I post this array :
$data = array(
'user_id' => $this->post('user_id'),
'group_id' => $this->post('group_id'),
'child_id' => $this->post('child_id'), //will be nested array
'custom' => $this->post('custom'),
'time' => $this->post('time'),
'date' => $this->post('date')
);
I tried to create a nested array with this : $this->post('child_id'), because user can post multiple child_id at once.
Then i tried to iterate through the child_id, because i need to insert them to the mysql :
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
What should i do, so i can have an array of child_id in my $data array? (nested array)
And how to iterate through it?
UPDATE :
I have updated the codes above.
I use advanced rest client for testing, and i tried to post something like this in the form content type :
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
Notice that theres two child_id (left most and right most), but only the last one (right most) is inserted.
And this is the add_trans in the model :
function add_trans($table, $data, $schedule_id) {
$query = $this->db->insert($table, array('child_id' => $data['child_id'], 'schedule_id' => $schedule_id));
return $query;
}
Thanks a lot for your time.
Even thought you set the name attribute as child[] on the markup,
You still need to call it as:
'child_id' => $this->post('child_id')
It will still return an array.
for($i = 0; $i < sizeof($data['child_id']); $i++) {
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data, $result_id[0]['id']);
}
EDIT:
Looking upon you query string, that seems to be the culprit:
child_id=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id=2
^ same index , same index, same index, it will overwrite and you will get only `2`
If you want to get them all into an array format, you need to set them like this
child_id[]=1&user_id=1&group_id=1&custom=&time=17%3A17%3A00&date=&child_id[]=2
^ it needs to be set like this
UPDATE:
And in your model, if you want each id per row, well you can also loop in this case:
function add_trans($table, $data, $schedule_id) {
foreach($data['child_id'] as $child_id) {
$query = $this->db->insert($table, array('child_id' => $child_id, 'schedule_id' => $schedule_id));
}
// return $this->db->insert_id();
return $query;
}
ofcourse that won't work, it has to be
for($i = 0; $i < sizeof($data['child_id']); $i++)
{
$result2 = $this->schedule_m->add_trans('transaction_schedule', $data['child_id'][$i], $result_id[0]['id']);
}
because you've not set $data['child_id[]'] so it doesn't exist, the key is just a string or number, it does not validate or parse anything
you don't need to give child[] in post method. just give only child, it will get complete array what are you sending from views
replace
'child_id' => $this->post('child_id[]')
with
'child_id' => $this->post('child_id')
Having some problems here, I think I am just overlooking something really simple...
I have a CMS that have multiple categories.
How do I create a variable or array that has the included categories groups that I want to use in my SHOW IF STATEMENT ??
So for example:
<?php
$catsrow = array(
'cat_1' => '41','46','62',
'cat_2' => '41','45','63',
'cat_3' => '41','43','65'
);
?>
<?php if
(catsrow[0] || catsrow[1] || catsrow[2]) == ($row_DetailRS1['category'])
{ echo 'do work' }
else { ?>
Thanks in advance!!
I guess what I am asking is, how do I compare an array with multiple groups inside. I need to compare different grouped categories..
Like $catsArray = ARRAY(cat_1 => '2,3,4' , cat_2 => '5,6,7' , cat_3 => '8,9,10')
if $row['cat_from_page'] == $catsArray (any of the groups) then SHOW THIS { }
????
you may need to explode the parts of the array
Kinda like $parts = explode(',' , $cat);
http://php.net/manual/en/function.explode.php
but you will need to implode the whole thing into one array
Like implode (',', $parts);
http://php.net/manual/en/function.implode.php
My Best guess at what you're trying to do:
$categories = array(
'cat_1' => array(
'41','46','62'
),
'cat_2' => array(
'41','45','63'
),
'cat_3' => array(
'41','43','65'
)
);
$row_DetailRS1['category'] = '41';
foreach($categories as $category => $items) {
foreach($items as $item) {
if($row_DetailRS1['category'] == $item) {
echo "Item: ".$item." found in Category: ".$category."\n";
}
}
}