0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ゆめみからの挑戦状 ★第5弾をいまごろトライする.

Last updated at Posted at 2024-04-26

ゆめみからの挑戦状 ★第5弾をいまごろトライする.

【お題】
以下のぐちゃぐちゃな配列を期待されている形に整形して出力してください

<?php
$in = [
    ['2nd' => 'two', 'four' => '4th'],
    'three' => '3rd',
    ['one' => '1st'],
    '10th' => 'ten',
    ['6th' => 'six'],
    '5th' => 'five',
    'seven' => '7th',
    ['fourteen' => '14th', '11th' => 'eleven'],
    ['8th' => 'eight'],
    'thirteen' => '13th',
    '12th' => 'twelve',
    'nine' => '9th',
    ['15th' => 'fifteen'],
];

意外にも簡単だった、邪道と言われてしまいそうな汎用性のないコードですが解けてしまったのでUPします.

<?php
class originSort
{
    /**
     * main
     * @param $in
     * @return array
     */
    public function main($in): array
    {
        $answerData = [];
        foreach ($in as $key => $value) {
            if (is_int($key)) {
                foreach ($value as $key2 => $value2) {
                    $answerData += $this->getAlignment($key2, $value2);
                }
            } else {
                $answerData += $this->getAlignment($key, $value);
            }
        }
        //ソート
        uksort($answerData, array($this, 'getSort'));
        return $answerData;
    }

    /**
     * 連想配列を置き換え
     * @param $key
     * @param $value
     * @return array
     */
    function getAlignment($key, $value): array
    {
        if (!(int)$key) {
            return [$value => $key];
        }
        return [$key => $value];
    }

    /**
     * ソート
     * @param $a 
     * @param $b
     * @return bool
     */
    function getSort($a, $b): bool
    {
        return (int)$a > (int)$b;
    }
}

$in = [
    ['2nd' => 'two', 'four' => '4th'],
    'three' => '3rd',
    ['one' => '1st'],
    '10th' => 'ten',
    ['6th' => 'six'],
    '5th' => 'five',
    'seven' => '7th',
    ['fourteen' => '14th', '11th' => 'eleven'],
    ['8th' => 'eight'],
    'thirteen' => '13th',
    '12th' => 'twelve',
    'nine' => '9th',
    ['15th' => 'fifteen'],
];

$answerData = (new originSort)->main($in);
//表示とアンサーデータ
foreach ($answerData as $key => $value) {
    printf('%s => %s <br>', $key, $value);
}
var_dump($answerData);

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?