如何获得特定条件下的数组值

时间:2018-11-24 02:36:07

标签: php arrays

我想问一些要根据得分键中的 最大得分 最小strlen 获取数组值的方法> 在单词键中,此示例数组:

<?php
$data = array(
  '0' => array('score' => '4','word' => 'titiek'),
  '1' => array('score' => '4','word' => 'titik'),
  '2' => array('score' => '4','word' => 'titie'),
  '3' => array('score' => '3','word' => 'tuatuka'),
  '4' => array('score' => '3','word' => 'titiks'),
);
$result = //do something??
print_r($result);
?>

让我们在$ data数组中看到,条件是最高分和最小strlen,我们有$ data [1]和$ data [2],对吗?但是,我需要第一个队列。结果print_r($result)是:

Array ( [score] => 4 [word] => titik )

3 个答案:

答案 0 :(得分:1)

您可以使用usort按照score然后按字长对数组进行排序,然后所需的结果将在$data[0]中。请注意,我们将相等的单词长度排在更高的位置,以便我们返回数组中看到的最短长度的第一个。

usort($data, function($a, $b) {
    if ($a['score'] == $b['score'])
        return (strlen($a['word']) >= strlen($b['word'])) ? 1 : -1;
    else
        return $b['score'] - $a['score'];
});
print_r($data[0]);

另一种方法(不依赖于usort行为)是找到最大分数,然后处理该数组以查找具有该分数的第一个最短字符串:

$max_score = max(array_column($data, 'score'));
$minlength = PHP_INT_MAX;
foreach ($data as $key => $value) {
    if ($value['score'] != $max_score) continue;
    if (strlen($value['word']) < $minlength) {
        $minlength = strlen($value['word']);
        $index = $key;
    }
}
print_r($data[$index]);

输出(两者相同):

Array ( 
    [score] => 4
    [word] => titik
)

Demo on 3v4l.org

答案 1 :(得分:1)

您可以使用array_reduce,并使用“> =”“ <=”将保留先前的值

$result = array_reduce($data, function ($previous, $current) {
  return $previous['score'] >= $current['score'] && strlen($previous['word']) <= strlen($current['word']) ? $previous : $current;
});

var_dump($result);

答案 2 :(得分:0)

在这里可以找到它:

$data = array(
  '0' => array('score' => '4','word' => 'titiek'),
  '1' => array('score' => '4','word' => 'titik'),
  '2' => array('score' => '4','word' => 'titie'),
  '3' => array('score' => '3','word' => 'tuatuka'),
  '4' => array('score' => '3','word' => 'titiks'),
);
$maxScore = 0; $minLen = 0;
foreach($data as $key => $arr) {
  $score = $arr['score'];
  $len = strlen($arr['word']);
  if($score > $maxScore) {
      $maxKey = $key;
      $minLen = $len;
      $maxScore = $score;
    } else if ($score == $maxScore && $len < $minLen) {
      $maxKey = $key;
      $minLen = $len;
    }
}
var_dump($data[$maxKey]);

我已经使用var_dump来显示结果。 $ data [$ maxKey] 是必需的结果。