This is my array:
$mygetting_id = $wpdb->get_results("SELECT DISTINCT post_id,meta_value from wp_postmeta Where meta_value LIKE '".$search_res[$k]."%' OR meta_value LIKE '%".$search_res[$k]."%' AND meta_key='my_profile_tags' ORDER BY post_id $limit");
foreach ( $mygetting_id as $post )
{
$id = $post->post_id;
$metaValue= esc_attr(get_post_meta($id, 'my_profile_tags',true));
$array_metaValue = explode(',',$metaValue);
$array_metaValue = array_map('strtolower', $array_metaValue);
$total_tags=count($array_metaValue);//like total=10
for($e=0;$e<=count($search_res);$e++)
{
$key = count( array_intersect( $array_metaValue, array_map('strtolower', $search_res ) ) );
}
// Get Percentage of each array result.
$percent=($key/$search_count)*100;
$percent=round($percent,0);
?>
//html part
} // for each close
Now I want to ORDER BY or show my result according to $percent variable then after show the results. I can't use the $percent var in my SQL statement. What should I do.
This is how it is displaying right now. I want the 400% to the top.

You can Order the results using PHP usort()
<?php
$mygetting_id = $wpdb->get_results("SELECT DISTINCT post_id,meta_value from wp_postmeta Where meta_value LIKE '".$search_res[$k]."%' OR meta_value LIKE '%".$search_res[$k]."%' AND meta_key='my_profile_tags' ORDER BY post_id $limit");
$sortedResults = array();
foreach ( $mygetting_id as $post )
{
$id = $post->post_id;
$metaValue= esc_attr(get_post_meta($id, 'my_profile_tags',true));
$array_metaValue = explode(',',$metaValue);
$array_metaValue = array_map('strtolower', $array_metaValue);
$total_tags=count($array_metaValue);//like total=10
for($e=0;$e<=count($search_res);$e++)
{
$key = count( array_intersect( $array_metaValue, array_map('strtolower', $search_res ) ) );
}
// Get Percentage of each array result.
$percent=($key/$search_count)*100;
$percent=round($percent,0);
// adding percent property to use it in usort
$post->percent = $percent;
$sortedResults[] = $post;
}
// sorting results
usort($sortedResults, function($a, $b){
// in case if they are equal
if($a == $b) return 0;
return $a->percent < $b->percent ? 1 : -1;
});
/// now your results are sorted do html part
foreach($sortedResults as $post){
// do your html here e.g
echo $post->id;
echo $post->percent . '%'; // etc
}
?>
or you can store percentage as separate field in the table and just ORDER BY score
You can use complex arithmetic operations in ORDER BY.
So, use the following.
$mygetting_id = $wpdb->get_results("SELECT DISTINCT post_id,meta_value from wp_postmeta Where meta_value LIKE '".$search_res[$k]."%' OR meta_value LIKE '%".$search_res[$k]."%' AND meta_key='my_profile_tags' ORDER BY
round(($key/$search_count)*100)
$limit");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With