Appending one array to another array in the same loop - mysql

This is for a custom Wordpress page but I think the basic array principles should apply. I've not worked with complex arrays before so am a little lost, trial and error hasn't worked yet.
I have a database of Posts, each post has meta_key's of 'shop' and 'expired'.
'expired' is a date (YYYY-MM-DD) which is used to tell the visitor when a Post's content expires and this key is what I'm trying to work with.
If a Post's 'expired' date is before today, they are shown 'Offer expired'
If the 'expired' date is in the future, they are shown 'Offer expires in X days' (this script isn't shown below, not necessary)
Posts are listed in order of their 'expired' date, ASC. The problem is that when a post expires I'd like that post to show at the end rather than stay on top.
Example of what I currently see:
Post 1 | Expired 3 days ago
Post 2 | Expired 1 day ago
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
And what I'd like to see (note Post X order):
Post 3 | Expires in 2 days
Post 4 | Expires in 6 days
Post 2 | Expired 1 day ago
Post 1 | Expired 3 days ago
This is my array code where I've attempted to merge the two
$postid = get_the_ID();
$meta1 = get_post_meta($postid, 'shop', true);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$today = date('Y-m-d', time());
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'paged' => $paged,
'posts_per_page' => '5',
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$args2 = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'shop',
'value' => $meta1
)
),
'meta_key' => 'expired',
'meta_value' => $today,
'meta_compare' => '<',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$final = $args + $args2;
$query = new WP_Query( $final );
while ( $query->have_posts() ) : $query->the_post(); ?>
HTML FOR DISPLAYING POST
endwhile;
At the moment it doesn't seem to take any notice of "$args2" and only displays $args
I'm sure my idea is on the right lines, needing to create two arrays and join them with the "+" rather than array_merge() but that's where I can't get any further.
Can someone kindly shed some light please? Thanks!

Now the solution you are trying to achieve is actually impossible if i understood your requirement properly. Let me explain why this is not achievable.
In your two arrays $args and $args2 most of the values are same leaving two odds , i am picking only one to just illustrate :
//it's in args
'meta_compare' => '>'
//it's in args2
'meta_compare' => '<'
Now what happens when you are trying to merge this two using array_merge($args , $args2):
'meta_compare' => '<'
That means it is taking 'meta_compare' from the later array which is $args2 here. This is the behavior of array_merge function defined in the doc:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one
Now if you are using + array union operator $args+$args2 :
'meta_compare' => '>'
That means it is taking 'meta_compare' from the first array which is $args here. This is the behavior of + array union operator defined in the doc :
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
Why it is happening because in the same level keys have to be unique . So in your situation they are in the same level :
$args = array ('key' => 'value1')
$args2= array ('key' => 'value2')
So only and only one value can exist here as in the merged array 'key' can point only one.
If this was the scenario :
$args [0] = array ('key' => 'value1' )
$args2 [1]= array ('key' => 'value2' )
Then both of the value stored by key will be resrved. This will be the resulting array :
array(2) {
[0]=>
array(1) {
["key"]=>
string(6) "value1"
}
[1]=>
array(1) {
["key"]=>
string(6) "value2"
}
}
Though i am not a geek of WP but as far as i understood from WP_query you can't pass args like this (I am not sure). So that leaves only one way to achieve this. You can pass these two args separately and merge the result as the result most probably (I am not sure) will be a 2D array you can merge them easily.
Hope that helps.
Happy coding :)

You can't just add 2 arrays together using the args+args2 syntax. PHP has no way of knowing what you mean by that. If you want the result to be an array containing both of these arrays, you could do this:
$final = array($args, $args2)
Otherwise I'm not sure how you want these two arrays combined. If you clarify how they need to be combined we might be able to help more.

Related

CakePHP 3 quoting function names defined in 'fields' configuration of my find() call

I am querying a database table conveniently named order and because of that I had to set 'quoteIdentifiers' => true in my app.php configuration. However, when I'm putting function names into the fields configuration of my find() call, CakePHP quotes them too.
$orders->find('all', array(
'fields' => array(
'DATE(Orders.date_added)',
'COUNT(*)',
),
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
));
The query above ends up calling
SELECT <...>, `DATE(Orders.date_added)` FROM `order` <...>
which obviously throws an error.
I googled a lot, tried this:
$orders = $orders->find('all', array(
'conditions' => array(
'Orders.order_status_id <>' => 0,
),
'group' => array(
'DATE(Orders.date_added)',
),
))->select(function($exp) {
return $exp->count('*');
});
and that didn't work either, throwing me some array_combine error.
Is there any way for me to un-quote those function names, while keeping the rest of the query quoted automatically? Here's what I'm trying to accomplish:
SELECT <...>, DATE(Orders.date_added) FROM `order` <...>
Please help.
You should use function expressions, they will not be quoted, except for arguments that are explicitly being defined as identifiers:
$query = $orders->find();
$query
->select([
'date' => $query->func()->DATE([
'Orders.date_added' => 'identifier'
]),
'count' => $query->func()->count('*')
])
->where([
'Orders.order_status_id <>' => 0
])
->group([
$query->func()->DATE([
'Orders.date_added' => 'identifier'
])
]);
I'd generally suggest that you use expressions instead of passing raw SQL snippets wherever possible, it makes generating SQL more flexible, and more cross-schema compatible.
See also
Cookbook > Database Access & ORM > Query Builder > Using SQL Functions

Replace variables extracted from database with theirs values

I'd like to translate a perl web site in several languages. I search for and tried many ideas, but I think the best one is to save all translations inside the mySQL database. But I get a problem...
When a sentence extracted from the database contains a variable (scalar), it prints on the web page as a scalar:
You have $number new messages.
Is there a proper way to reassign $number its actual value ?
Thank you for your help !
You can use printf format strings in your database and pass in values to that.
printf allows you to specify the position of the argument so only have know what position with the list of parameters "$number" is.
For example
#!/usr/bin/perl
use strict;
my $Details = {
'Name' => 'Mr Satch',
'Age' => '31',
'LocationEn' => 'England',
'LocationFr' => 'Angleterre',
'NewMessages' => 20,
'OldMessages' => 120,
};
my $English = q(
Hello %1$s, I see you are %2$s years old and from %3$s
How are you today?
You have %5$i new messages and %6$i old messages
Have a nice day
);
my $French = q{
Bonjour %1$s, je vous vois d'%4$s et âgés de %2$s ans.
Comment allez-vous aujourd'hui?
Vous avez %5$i nouveaux messages et %6$i anciens messages.
Bonne journée.
};
printf($English, #$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});
printf($French, #$Details{qw/Name Age LocationEn LocationFr NewMessages OldMessages/});
This would be a nightmare to maintain so an alternative might be to include an argument list in the database:
#!/usr/bin/perl
use strict;
sub fetch_row {
return {
'Format' => 'You have %i new messages and %i old messages' . "\n",
'Arguments' => 'NewMessages OldMessages',
}
}
sub PrintMessage {
my ($info,$row) = #_;
printf($row->{'Format'},#$info{split(/ +/,$row->{'Arguments'})});
}
my $Details = {
'Name' => 'Mr Satch',
'Age' => '31',
'LocationEn' => 'England',
'LocationFr' => 'Angleterre',
'NewMessages' => 20,
'OldMessages' => 120,
};
my $row = fetch_row();
PrintMessage($Details,$row)

CakePHP find query using %like% with spaces

I'm trying to query a page based on either a category ID or sub category name.
The variable $cat will either have an integer or varchar grabbed from my database.
I've been using cakephp 1.3 with a sql find all articles with a category of $cat OR sub-category LIKE $cat
It works great but a problem arises when $cat has a space between words, "google forms".
I've looked through this site and tried a number of methods with no luck. Appreciate any advice.
Here's my controller routines:
$cat = Sanitize::escape($cat);
$cat = trim($cat);
$title_a = str_replace($cat, "%".$cat."%", $cat);
$a_t = str_replace('"', $title_a, $title_a);
//var_dump($cat);
if(!empty($cat))
{
$sqlConditions = array('OR'=>array('Article.categories LIKE' => $a_t, 'Article.event_category_id' => $cat));
$sqlParams = array('conditions'=>$sqlConditions);
$catdata=$this->Article->find('all',$sqlParams);
return $catdata;
}
I've tried many different alternatives:
RLIKE instead of LIKE
Different query using MATCH
$sqlConditions = array(
'OR' => array(
'MATCH(Article.categories AGAINST(? IN BOOLEAN MODE)' => $cat,
'MATCH(Article.event_category_id) AGAINST(? IN BOOLEAN MODE)' => $cat
)
);
$sqlConditions = array('OR'=>array('Article.categories LIKE' => "%".$cat."%", 'Article.event_category_id' => $cat));
I think a decent solution would be to remove all of the spaces and make the characters of $cat lower case.
$likeCat = strtolower(str_replace(' ', '', trim($cat)));
$sqlConditions = array(
'OR'=> array(
'LOWER(REPLACE(Article.categories, ' ', ''))' => $likeCat,
'Article.event_category_id' => $cat
)
);

return only column name values from mysql table

sorry but i didn't knew how to explain the question in on sentence...
actually i have code like this when i do mysql_fetch_array...
[0] => 10
[id] => 10
[1] => 58393
[iid] => 58393
[2] => 0
[ilocationid] => 0
[3] => 38389
[iapptid] => 38389
[4] => 2012-06-30T00:00:00
[ddate] => 2012-06-30T00:00:00
[5] => 1000
[ctimeofday] => 1000
but i want to return something like this
[id] => 10
[iid] => 58393
[ilocationid] => 0
[iapptid] => 38389
[ddate] => 2012-06-30T00:00:00
[ctimeofday] => 1000
i mean without the numeric representatives of the columns. how do i do it...please help...
As explained in the manual for PHP's mysql_fetch_array() function:
The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
Therefore, you want either:
mysql_fetch_array($result, MYSQL_ASSOC);
or
mysql_fetch_assoc($result);
Note however the warning:
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_fetch_array()
PDOStatement::fetch()

Joins - Merge result into single, multidimensional array

I'm performing a simple query that joins two tables together. What I get is something like this.
array(
[0] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'id' => 52
'name' => 'charles',
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
);
...which is the expected result. However, I'd like the query to return something like this:
array(
[0] => array(
'id' => 52,
'name' => 'charles',
'sales' => array(
[0] => array(
'sale_id' => 921,
'sale_time' => 1306393996,
'sale_price' => 54.21
),
[1] => array(
'sale_id' => 922,
'sale_time' => 1306395000,
'sale_price' => 32.41
),
...
)
)
)
Now I realize I could simply perform two queries, one for the user info, and another for sales, and merge those arrays together using whatever language I'm using (PHP in this case). But I have many arrays of properties and querying and merging for those seems awfully inelegant to me (although it does work). It seems to me there'd be a way to work with a single, unified object without duplicating data.
Just wondering if there was a no-brainer query, or if that's simply not easy through MySQL alone.
I would say this is not possible with MySQL alone - you have to do some tricks at application level. That is, because even if you send a single query that will bring you all the data from MySQL to your application (PHP), they will come as a denormalized array of data - your first case.
If you want to get the data as in your second case, I'd recommend using some ORM - in Ruby there is ActiveRecord, in Perl there are Class::DBi, DBIx::Class and many more - I can not name one for PHP that is able to do this, but I am sure there are plenty.