Optimized code for only max value in array in php [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
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)),
)
);

Related

PHP: can't add to empty associative array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
i'm missing something simple here trying to add a new key/value pair and then add to the value of that pair as this loop goes on. this throws an undefined index error:
$someAssocArray = [2] => 'flarn'
[3] => 'turlb'
$someOtherAssocArray = [0] => 'id' => '11'
'name' => 'flarn'
[1] => 'id' => '22'
'name' => 'turlb'
[2] => 'id' => '33'
'name' => 'turlb'
[3] => 'id' => '44'
'name' => 'flarn'
$idList = [];
foreach($someAssocArray as $key=>$value) {
foreach($someOtherAssocArray as $item) {
if($item['name'] === $value) {
$idList[$value] += $item['id'];
}
}
}
the end result of idList should look like this:
$idList = [ "flarn" => "11,44"
"turlb" => "22,33" ]
so please tell me what i'm missing so i can facepalm and move on.
[Edit] OK I just re-read that question and I might be misunderstanding. Is the desired output of 11,44 supposed to represent the sum of the values? Or a list of them?
This code will generate a warning if $idList[$value] doesn't exist:
$idList[$value] += $item['id'];
This is happening because it has no value yet for the first time you're incrementing. You can avoid this issue by initializing the value to zero for that first time when it doesn't exist:
If you want a sum of the values:
if($item['name'] === $value) {
$idList[$value] ??= 0; // initialize to zero
$idList[$value] += $item['id']; // add each value to the previous
}
If you want a list of the values:
if($item['name'] === $value) {
$idList[$value] ??= []; // initialize to an empty array
$idList[$value][] = $item['id']; // append each element to the list
}
(Then you can use implode() to output a comma-separated string if desired.)

PHP: Getting values by date [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Im new In PHP!.
I have an array that contains dates and vlaues. How do i get all values of
specific date?. EXp: I would like to get all values from year 2015. If someone Knows can guide me.
You could use array_filter, then check the array key substr matches the date.
<?php
$date = 2016;
$array = [
'2016-01-01' => 'a',
'2016-01-02' => 'b',
'2016-12-01' => 'c',
'2017-01-04' => 'd',
'2017-01-05' => 'e',
'2017-01-06' => 'f',
];
$result = array_filter($array, function ($key) use ($date) {
return substr($key, 0, strlen($date)) == $date;
}, ARRAY_FILTER_USE_KEY);
print_r($result);
https://3v4l.org/UYaQq
Result:
Array
(
[2016-01-01] => a
[2016-01-02] => b
[2016-12-01] => c
)
<?php
$array = array('2015-01-01' => "test1",
'2013-02-04' => "test2",
'2011-03-08' => "test3",
'2016-03-08' => "test3");
foreach( $array as $key => $value ){
if(date('Y',strtotime($key)) >= 2015)
echo $value . ", ";
}
?>
An Array Contains a Key and a Value. The Key in your case is the Date. And the Value is... the value
You define it like this
$array = array(
Date => Value,
AnotherDate => AnotherValue,
);
or since PHP5
$array = [
Date => Value,
AnotherDate => AnotherValue,
];
if you now look at your Array using
var_dump($array);
You'll see the date is already combined with your value and It will even show the type of value (boolean, string, integer...)
Edit
Anotherone was faster

how to sort an array based on a different array in php? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i have this array
array(
'pc' => array('count'=>3),
'xbox' => array('count'=>3),
'wii' => array('count'=>3),
'3ds' => array('count'=>3),
'other' => array('count'=>3),
)
and i want to order it like
array(
'wii' => array('count'=>3),
'xbox' => array('count'=>3),
'other' => array('count'=>3),
'3ds' => array('count'=>3),
'pc' => array('count'=>3),
)
im thinking that i need to have another array to sort it by??
the keys might not be the same, so i think an isset() is in order at one point
edit: the criteria is the second array keys
any ideas?
You will have to define a custom sorting algorithm. You can do that by using PHP's uksort() function. (The difference to the very similar usort() function being that it compares the array's keys instead of its values.)
It could look somewhat like this (requires PHP >= 5.3 because of the anonymous functions I use in it):
<?php
$input = array(
'pc' => array('count'=>3),
'xbox' => array('count'=>3),
'wii' => array('count'=>3),
'3ds' => array('count'=>3),
'other' => array('count'=>3),
);
$keyOrder = array('wii', 'xbox', 'other', '3ds', 'pc');
uksort($input, function($a, $b) use ($keyOrder) {
// Because of the "use" construct, $keyOrder will be available within
// this function.
// $a and $b will be two keys that have to be compared against each other.
// First, get the positions of both keys in the $keyOrder array.
$positionA = array_search($a, $keyOrder);
$positionB = array_search($b, $keyOrder);
// array_search() returns false if the key has not been found. As a
// fallback value, we will use count($keyOrder) -- so missing keys will
// always rank last. Set them to 0 if you want those to be first.
if ($positionA === false) {
$positionA = count($keyOrder);
}
if ($positionB === false) {
$positionB = count($keyOrder);
}
// To quote the PHP docs:
// "The comparison function must return an integer less than, equal to, or
// greater than zero if the first argument is considered to be
// respectively less than, equal to, or greater than the second."
return $positionA - $positionB;
});
print_r($input);

Sort PHP Numerically & Identify which is closest to date [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got an array for events on my site that looks like this:
array(
'title' => 'Name',
'link' => 'http://www.eventssite.com',
'image' => '_img/event_img.jpg',
'location' => 'Florida, US',
'year' => '2013',
'date' => 'Dec. 12-14',
'desc' => 'Description about the event.',
'dateid' => '1212013'
),
I'd like to sort the array before the foreach by the dateid so that they show in the proper Date order.
Additionally I'm trying to identify which one of the events is closest to the actual date, as I am using a carousel type system that needs to know which to display first.
I've researched usort and am not able to get it to go on my own, Thank you for any assistance on these!
Using this function: http://php.net/usort
An example would be something like:
<?php
//just an array of arrays with the date as one of the values of the array
$array = array(
array(
'date' => '05/02/1988',
'name' => 'Jacob'
),
array(
'date' => '12/12/1968',
'name' => 'Sherry'
),
array(
'date' => '05/15/1978',
'name' => 'Dave'
)
);
//usort is used for non conventional sorting.
//which could help in this case
//NOTICE - we are not setting a variable here!
//so dont call it like $array = usort(...) you will just be setting $array = true
usort($array,'sortFunction');
//display the results
var_dump($array);
//function called by usort
function sortFunction($a,$b){
//turn the dates into integers to compare them
//
$strA = strtotime($a['date']);
$strB = strtotime($b['date']);
//don't worry about sorting if they are equal
if($strA == $strB){
return 0;
}
else{
//if a is smaller than b, the move it up by one.
return $strA < $strB ? -1 : 1;
}
}
?>
(in case youre interested, line 40 is called a Ternary)
edited for clarity

Replace first level array keys using values from a specific column [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 10 months ago.
Improve this question
I have an array like this
$users = array(
[0] => array('Id' => 3, 'Name' => 'Bob'),
[1] => array('Id' => 8, 'Name' => 'Alice'),
)
and I want to pull the Ids 'up' one level so that the final array is:
$usersById = array(
[3] => array('Id' => 3, 'Name' => 'Bob'),
[8] => array('Id' => 8, 'Name' => 'Alice'),
)
The Id values are unique.
Is there a native PHP way to do this? The code I'm currently using is:
$usersById = array();
foreach ($users as $key => $value)
{
$usersById[$value['Id']] = $value;
}
This works, but is not terribly elegant.
Modern answer (requires PHP 5.5)
The new function array_column is very versatile and one of the things it can do is exactly this type of reindexing:
// second parameter is null means we 're just going to reindex the input
$usersById = array_column($users, null, 'Id');
Original answer (for earlier PHP versions)
You need to fetch the ids from the sub-arrays with array_map, then create a new array with array_combine:
$ids = array_map(function($user) { return $user['Id']; }, $users);
$users = array_combine($ids, $users);
The code above requires PHP >= 5.3 for the anonymous function syntax, but you can also do the same (albeit it will look a bit uglier) with create_function which only requires PHP >= 4.0.1:
$ids = array_map(create_function('$user', 'return $user["Id"];'), $users);
$users = array_combine($ids, $users);
See it in action.
You could use the array_reduce() function, like:
$usersById = array_reduce($users, function ($reduced, $current) {
$reduced[$current['Id']] = $current;
return $reduced;
});
However, it's no more elegant than a foreach.
I think using foreach is much more elegant. Maybe you just only want to write it differently:
$keyed = array();
foreach($users as $w) $keyed[$w['Id']] = $w;
In case you want to replace the existing array, foreach is not that flexible indeed. But maybe the following is some sort of alternative:
$users = function($key) use ($users)
{
foreach($users as $v) $keys[] = $v[$key];
return array_combine($keys, $users);
};
$users = $users('Id');
It allows the callback to accept parameters, e.g. the name of the key which should be used to create the new keys from.
And one more variant using array_walk:
$usersById = array();
array_walk($users, function($val) use (&$usersById) {
$usersById[$val['Id']] = $val;
});

Categories