Order array result using $ percent php variable
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
either show the result according to the variable $percent
and then show the results. I cannot use var $percent
in my SQL statement. What should I do?
This is how it is displayed right now. I want 400% to the top.
+3
source to share
3 answers
You can order 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 the percentages as a separate field in the table and just ORDER BY
score
+1
source to share
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");
+1
source to share