使用$percent变量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");
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
现在我要ORDER BY或根据$percent变量显示结果,然后显示结果.我无法在SQL语句中使用$percent var.我该怎么办.
这就是现在显示的样子.我希望将400%提高到最高.
解决方法:
您可以使用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
}
?>
或者您可以将百分比存储为表格中的单独字段,而仅按ORDER BY得分
标签:foreach,sql-order-by,php 来源: https://codeday.me/bug/20191120/2047649.html