duanlan2003 2015-06-03 20:01
浏览 4
已采纳

在php中仅为数组中的最大值优化代码[关闭]

hi there I designed a blog page....per page 10 artilcs!

I want return biggest time (stamptime) for each 10 articls (like publish up time,publish down time,created,modifed time) to create meta tag.

so I have a list of 10 artiles (each article is an array with all parameters like date,content,title,...) that I saved them in $list array.

like this:

$list =  array ( array('id' => '1', 'modifed ' => '123123123' ...

I want return biggest value...the articls are mixed.

I use this code:

   $data['created'] = array_reduce($list, function ($a, $b) {
        return @$a['created'] > $b['created'] ? $a : $b ;

    $data['modified'] = array_reduce($list, function ($a, $b) {
        return @$a['modified'] > $b['modified'] ? $a : $b ;

    $data['publish_up'] = array_reduce($list, function ($a, $b) {
        return @$a['publish_up'] > $b['publish_up'] ? $a : $b ;

    $data['publish_down'] = array_reduce($list, function ($a, $b) {
        return @$a['publish_down'] > $b['publish_down'] ? $a : $b ; 

My only worry is it maybe has a bad effect in my loading page.

do you think this code is Optimized?

  • 写回答

1条回答 默认 最新

  • dqf60304 2015-06-03 20:50
    关注

    Here's my solution. But as Sven said, you need to be more specific.

    //fake data
    $data = array(
        array('id' => 1, 'upd' => 111, 'created' => 333),
        array('id' => 2, 'upd' => 1203, 'created' => 43),
        array('id' => 3, 'upd' => 144, 'created' => 533),
    );
    
    // here, I'm first computing the max of each column
    // I place the results in an array and returns ultimately the max
    echo max(
        array(
            max(array_column($data, 'upd')),
            max(array_column($data, 'created'))
        )
    );
    // here, it returns 1203, as there is an element "upd" with value 1203
    

    If you do not have php 5.5, you have the following options:

    1. use a php implementation that matches the behaviour of php 5.5 : https://github.com/ramsey/array_column/blob/master/src/array_column.php

    2. upgrade to php 5.5 ;)

    3. implements the function with map

    The option 3 leads to the following code:

    echo max(
        array(
            max(array_map(function($arr){return $arr['upd'];}, $data)),
            max(array_map(function($arr){return $arr['created'];}, $data)),
        )
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路