Wordpress sql,基于元值重新排序数组



在我的wordpress函数文件中,我只得到post id的sql查询结果,然后将这些id创建一个数组,我发送到我的页面。

这工作完美,但我想根据我在数组过程中生成的值之一重新排序。我有一个'featured'的值,我想让它,所以任何结果,其中featured = 1是第一个在数组中。

$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt = 0; 
$imgpath = '';

if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){


$ress[$cnt]['featured']  = get_post_meta($id,'_awpcp_is_featured',true);

$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$cnt]['imgs'] = $imgpath;
}else{
$ress[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}                       
$cnt++;
}
}
echo json_encode($ress);
}

是否有一种方法可以简单地使用条件,以便将这些值首先放在数组中?

在数组中使用get_post_meta函数是不好的做法。我建议首先查询数据库,从自定义字段中提取数据。

然而,我认为有两种方法可以回答你的问题:

  1. 使用两个数组并在迭代后合并:
$myresults = $wpdb->get_results( $sqlStatement );
$ress1 = $ress2 = array();
$cnt = 0; 
$imgpath = '';

if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');

$array_name = !empty($is_featured) ? 'ress1' : 'ress2';

$$array_name[$cnt]['featured']  = $is_featured;
if($imgpath){
$$array_name[$cnt]['imgs'] = $imgpath;
}else{
$$array_name[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
$ress = array_merge($ress1, $ress2);
echo json_encode($ress);
}
  1. 使用2个计数器:
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt1 = 0;
$cnt2 = 1000000; 
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){

$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$counter_name = !empty($is_featured) ? 'cnt1' : 'cnt2';
$ress[$$counter_name]['featured']  = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$$counter_name]['imgs'] = $imgpath;
}else{
$ress[$$counter_name]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$$counter_name++;
}
}
$ress = array_values( $ress );
echo json_encode($ress);
}

最新更新