在array_keys中找到max,键是字符串php

时间:2017-10-29 16:08:11

标签: php arrays

基本上,我使用以下方法操作数组:

$block = array_count_values(array_column($modelLokasi, 'block'));

结果如下,

[
  'A1' => 14
  'A2' => 13
  'A3' => 20
  'A9' => 7
  'B7' => 11
  'C1' => 7
  'C2' => 10
  'C3' => 15
  'C4' => 11
  'C6' => 12
  'C7' => 8
  'D7' => 31
  'E1' => 23
  'E2' => 30
  'E3' => 20
  'E4' => 28
  'E7' => 12
  'F7' => 1
  'G1' => 2
  'G2' => 10
  'G3' => 18
  'G4' => 21
  'G5' => 1
  'G6' => 1
  'G7' => 10
  'H7' => 11
  'I1' => 8
  'I2' => 13
  'I3' => 16
  'I4' => 17
  'I5' => 12
  'I6' => 15
  'I7' => 11
  'K0' => 28
  'K1' => 21
  'K2' => 2
  'K7' => 36
] 

如何在键中找到最大第一个字符,在键中找到最大第二个字符。 我的意思是K中的max_first_character = k79中的max_second_character = A9

因为我需要像这样显示它:

  | A  |  B  |  C  |  ....  |  K  |
 1| 14 |  0  |                    |
 2| 13 |''''''''''''''''''''|     |
 3| 20 |''''''''''''''''''''|     |
 4| 0  |''''''''''''''''''''|     |
 5| 0  |''''''''''''''''''''|     |
 6| 0  |''''''''''''''''''''|     |
 7| 0  |''''''''''''''''''''| 36  |
 8| 0  |''''''''''''''''''''|     |
 9| 7  |''''''''''''''''''''|     |

请告知。

1 个答案:

答案 0 :(得分:1)

你可以这样做:     

$data = [
  'A1' => 14,
  'K10' => 15,
  'ZZ5' => 23,
];

$maxLetters = null;
$maxDigits = null;
foreach ($data as $key => $value) {
    if (!preg_match('/^([A-Z]*)(\d*)$/', $key, $matches)) {
        throw new \InvalidArgumentException(sprintf('Key %s is not in appropriate format', $key)); 
    }
    $letters = $matches[1];
    $digits = intval($matches[2]);
    $maxLetters = $maxLetters === null ? $letters : (strcmp($letters, $maxLetters) ? $letters : $maxLetters);
    $maxDigits = $maxDigits === null ? $digits : max($digits, $maxDigits);
}

echo "$maxLetters $maxDigits";