我在mysql中从query中获得了这个对象数组,我需要
[
{
"id": "11",
"from_userid": "1996",
"contest_id": "29",
"to_userid": "8",
"vote_date": "2020-10-06 01:40:04",
"count_votes": "1"
},
{
"id": "1",
"from_userid": "82",
"contest_id": "29",
"to_userid": "94",
"vote_date": "2020-09-03 07:06:36",
"count_votes": "1"
},
{
"id": "2",
"from_userid": "82",
"contest_id": "29",
"to_userid": "98",
"vote_date": "2020-09-03 07:06:36",
"count_votes": "0"
}
]我需要的对象有最高的'count_votes‘为例如- id-11和1有类似的计数投票。所以函数应该返回这两个对象。
我使用的函数只返回一个对象。我需要这两个对象,除了最高的(Count_votes)对象。预期输出-
[
{
"id": "11",
"from_userid": "1996",
"contest_id": "29",
"to_userid": "8",
"vote_date": "2020-10-06 01:40:04",
"count_votes": "1"
},
{
"id": "1",
"from_userid": "82",
"contest_id": "29",
"to_userid": "94",
"vote_date": "2020-09-03 07:06:36",
"count_votes": "1"
}
]使用的函数-
function max_attribute_in_array($array, $prop) {
return max(array_map(function($o) use($prop) {
return $o;
},
$array));
}我也试过了-
function get_highest($arr) {
$max = $arr[0]; // set the highest object to the first one in the array
foreach($arr as $obj) { // loop through every object in the array
$num = $obj['count_votes']; // get the number from the current object
if($num > $max['count_votes']) { // If the number of the current object is greater than the maxs number:
$max = $obj; // set the max to the current object
}
}
return $max; // Loop is complete, so we have found our max and can return the max object
}发布于 2020-10-06 17:40:35
您可以使用array_column将所有count_votes值提取到一个数组中,然后您可以获取以下内容的max:
$max = max(array_column($arr, 'count_votes'));然后,可以根据等于$max的count_votes值对数组执行array_filter操作
$out = array_filter($arr, function ($o) use ($max) {
return $o['count_votes'] == $max;
});输出:
Array
(
[0] => Array
(
[id] => 11
[from_userid] => 1996
[contest_id] => 29
[to_userid] => 8
[vote_date] => 2020-10-06 01:40:04
[count_votes] => 1
)
[1] => Array
(
[id] => 1
[from_userid] => 82
[contest_id] => 29
[to_userid] => 94
[vote_date] => 2020-09-03 07:06:36
[count_votes] => 1
)
)发布于 2020-10-06 17:41:59
注max与单级数组一起工作,因此所有对象都会在内部转换为整数。
正如@Nick所指出的,你的get_highest可以通过PHP函数来实现:
function get_highest($array, $prop) {
return max(array_column($array, $prop));
}因此,您所要做的就是根据此get_highest过滤数组
$max = get_highest($myArray, 'count_votes');
$maxes = array_filter($myArray, fn($obj) => $obj['count_votes'] === $max);发布于 2020-10-06 18:26:49
function get_heighest($arr){
$newArray = array();
$voteCount = 0;
foreach($arr as $obj){
if($obj['count_votes'] >= $voteCount){
array_push($newArray, $obj)
$voteCount = $obj['count_votes'];
}else{
$i = 0;
foreach($newArray as $object){
if($object['count_votes'] < $voteCount){
unset($newArray[$i]);
}
$i++;
}
}
}
return $newArray;
}https://stackoverflow.com/questions/64223167
复制相似问题