如何在二维数组中找出temp最大值所在行的time与temp
解决方案
一、二维数组中获取最高温度对应的时间与温度值
针对你提供的PHP格式天气数组,无需先单独查找最高温度再二次遍历,一次遍历即可同时记录最高温度及对应条目,避免字符串比较误差,代码示例如下:
$weatherData = [ ['time' => '00:00', 'temp' => '15.1'], ['time' => '00:00', 'temp' => '15.1'], ['time' => '00:01', 'temp' => '15.1'], ['time' => '00:02', 'temp' => '15.1'], ['time' => '00:02', 'temp' => '15.1'], ['time' => '00:02', 'temp' => '15.0'], ['time' => '00:03', 'temp' => '15.0'], ]; $maxTemp = -INF; $maxEntry = null; foreach ($weatherData as $entry) { // 将温度转为浮点型,避免字符串比较逻辑错误 $currentTemp = (float)$entry['temp']; if ($currentTemp > $maxTemp) { $maxTemp = $currentTemp; $maxEntry = $entry; } // 若需保留所有最高温度条目,可将$maxEntry改为数组,此处追加即可 } // 输出结果 if ($maxEntry) { echo "最高温度时间:{$maxEntry['time']},温度:{$maxEntry['temp']}"; }
关键说明:
- 强制将
temp转为浮点型,避免字符串比较的坑(例如'9.9'字符串会被误判为大于'15.1') - 一次遍历完成数据筛选,比“先找最大值再遍历匹配”更高效
二、WordPress中减少WP_Queries数量的实用方法
1. 修改主查询替代新建WP_Query
通过pre_get_posts钩子修改默认主查询,避免重复新建查询实例:
add_action('pre_get_posts', function($query) { // 仅前台主查询生效,避免影响后台操作 if (!is_admin() && $query->is_main_query()) { // 按需设置参数,示例:指定文章类型、每页数量 $query->set('post_type', 'post'); $query->set('posts_per_page', 5); // 仅获取文章ID,减少数据库返回字段 $query->set('fields', 'ids'); } });
2. 缓存查询结果
对重复调用的查询结果进行缓存,避免重复请求数据库:
$popularPosts = wp_cache_get('popular_posts'); if (!$popularPosts) { $args = [ 'post_type' => 'post', 'orderby' => 'comment_count', 'posts_per_page' => 3, ]; $popularPosts = new WP_Query($args); // 缓存1小时,可按需调整时长 wp_cache_set('popular_posts', $popularPosts, '', 3600); } if ($popularPosts->have_posts()) { while ($popularPosts->have_posts()) { $popularPosts->the_post(); // 输出文章内容逻辑 } wp_reset_postdata(); }
3. 合并查询与轻量化查询
- 合并多个同类查询:将多个需要获取的数据集通过分类、标签或自定义字段合并为单个查询
- 用
get_posts替代WP_Query:仅需文章数据时,get_posts返回更轻量的文章数组,无需重置全局$post变量 - 关闭不必要的缓存:查询时关闭无需的元数据或评论缓存,减少数据库负载:
$args = [ 'post_type' => 'post', 'posts_per_page' => 10, 'update_post_meta_cache' => false, 'update_comment_cache' => false, ]; $posts = get_posts($args);
内容的提问来源于stack exchange,提问作者geekcohen
相关产品推荐
相关产品推荐

