doulangbizhan5160 2018-06-20 11:44 采纳率: 100%
浏览 113

PHP数组没有按顺序显示

Hi I have a WordPress site with an array with elements in, and I when I loop through the array I want the fields to display in the order as it is set in the array. For example:

My array:

$metas = get_post_meta($post->ID);
$metatodisplay = array('address', 'county', 'postcode', 'region', 'telephone', 'fax', 'email', 'website', 'contact', 'cab_member_since', 'twitter', 'linkedin');

My foreach loop:

foreach($metas as $key=>$value){
   if(in_array($key, $metatodisplay)){
     echo $key;
   }    
}

I want the array values to display in the order as shown in the $metatodisplay array. At this point they are just random on several pages, and on others they display correctly.

  • 写回答

1条回答 默认 最新

  • duancha1065 2018-06-20 11:45
    关注

    This should work:

    foreach($metatodisplay as $key){
       if(isset($metas[$key])){
         echo $key;
       }    
    }
    

    Your code runs all values from $metas in their order and compares them to $metatodisplay (while the order of $metatodisplay is not taken into account). The changed code uses the exact order of $metatodisplay, ignoring the order within $metas.

    If you want to do something with the values from $metas, you can simply accessing them, for example through echo $metas[$key]

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大