2

Basically, I have manipulate an array using :

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

The result like this,

[
  '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
] 

How to find max first character in keys and max second character in keys. I mean max_first_character is = K in k7 and max_second_character = 9 in A9 ?

Because I need to display it like this :

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

Please advise.

2
  • Sort your array then get the keys of the last and second to last (Or first ans second depending how you sort it). Commented Oct 29, 2017 at 16:11
  • Please see my update Commented Oct 29, 2017 at 16:16

1 Answer 1

1

You can do it such a way:

$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";
Sign up to request clarification or add additional context in comments.

3 Comments

@FadlyDzil, isn't my answer still solve the problem?
Sorry @Ivan Kalita, There is problem if the key have two digits. Let say A10. It return 1 not 10. Please advise]
@FadlyDzil, I updated the answer. It now supports many chars and many digits :) I replaced str_split by preg_match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.