在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?
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:
use a php implementation that matches the behaviour of php 5.5 : https://github.com/ramsey/array_column/blob/master/src/array_column.php
upgrade to php 5.5 ;)
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)),
)
);