質問: 規則性がある配列名のキー毎に新たな配列を生成したい ■やりたいこと ・元配列の配列名「○○_数字」の数字が小さい順に並べ替えた後、キー毎に新たな配列を作成したいです ■元配列 [test_1] => array ( [0] => dummy1_0 [1] => [2] => dummy1_2 ) [test_3] => array ( [0] => [1] => dummy3_1 [2] => ) [test_2] => array ( [0] => dummy2_0 [1] => [2] => dummy2_2 ) [test_4] => array ( [0] => [1] => dummy4_1 [2] => ) ■作成したい配列 [result_1] => array ( [0] => dummy1_0 [1] => dummy2_0 [2] => [3] => ) [result_2] => array ( [0] => [1] => [2] => dummy3_1 [3] => dummy4_1 ) [result_3] => array ( [0] => dummy1_2 [1] => dummy2_2 [2] => [3] => )
回答: http://ideone.com/ncp9f5 array( 0 => 'dummy1_0', 1 => '', 2 => 'dummy1_2', ), 'test_3' => array( 0 => '', 1 => 'dummy3_1', 2 => '', ), 'test_2' => array( 0 => 'dummy2_0', 1 => '', 2 => 'dummy2_2', ), 'test_4' => array( 0 => '', 1 => 'dummy4_1', 2 => '', ), ); $max = 0; $result = array(); array_walk_recursive($test, function ($v) use (&$max) { if (preg_match('/\a[^\d]++(\d++)_\d++\z/', $v, $matches)) { $max = max((int)$matches[1], $max); } }); if ($max > 0) { array_walk_recursive($test, function ($v) use (&$result, &$max) { if (preg_match('/\a[^\d]++(\d++)_(\d++)\z/', $v, $matches)) { $title = 'result_' . ($matches[2] + 1); if (!isset($result[$title])) { $result[$title] = array_fill(0, $max, ''); } $result[$title][$matches[1] - 1] = $v; } }); } uksort($result, 'strnatcmp'); print_r($result);