在我的 wordpress 函式檔案中,我只獲得了帖子 ID 的 sql 查詢結果,然后使用這些 ID 創建一個發送到我的頁面的陣列。
這完美地作業,但我想根據我在陣列程序中生成的值之一重新排序它。我有一個 'featured' 的值,我想讓它使所有 features = 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);
}
有沒有辦法簡單地使用條件來將這些值放在陣列的首位?
uj5u.com熱心網友回復:
在陣列中使用函式 get_post_meta 是不好的做法。我建議首先查詢資料庫以從自定義欄位中提取資料。
但是,我認為有兩種方法可以回答您的問題:
- 使用 2 個陣列并在迭代后將它們合并在一起:
$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);
}
- 使用 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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480611.html
