すべての配列エントリのキーを取得し、それらをアンダースコア文字 (_) で分割してから、配列に入れます。
$a = array(
'foo_1' => 'Dog',
'bar_2' => 'Cat',
'baz_3' => 'Fish',
'foo_1' => 'Frog',
'bar_2' => 'Bug',
'baz_3' => 'Ddd',
...
);
$arrays = array(
'foo' => array(),
'bar' => array(),
'baz' => array()
);
foreach ($a as $k => $v) {
$s = explode("_", $k);
if (!isset($arrays[$s[0]])) {
$arrays[$s[0]] = array();
}
$arrays[$s[0]][$s[1]] = $v; // This line if you want to preserve the index (1, 2, ...)
$arrays[$s[0]][] = $v; // Or this line if you want to reindex the arrays.
// Comment or remove one of these two lines.
}
次に、多次元配列があります。
array(
'foo' => array(
"Dog",
"Frog"
),
'bar' => array(
"Cat",
"Bug"
),
'baz' => array(
"Fish",
"Ddd"
),
...
)
上記の多次元配列を使用することをお勧めしますが、 「キー」 (「foo」、「bar」など)ごとに新しい変数を作成する場合は、次のスニペットを使用します。
$a = array(
'foo_1' => 'Dog',
'bar_2' => 'Cat',
'baz_3' => 'Fish',
'foo_1' => 'Frog',
'bar_2' => 'Bug',
'baz_3' => 'Ddd',
...
);
foreach ($a as $k => $v) {
$s = explode("_", $k);
${$s[0]}[$s[1]] = $v; // This line if you want to preserve the index (1, 2, ...)
${$s[0]}[] = $v; // Or this line if you want to reindex the arrays.
// Comment or remove one of these two lines.
}
配列$a
にいくつかの重複キーがあることに注意してください。これは PHP では不可能です。
編集:あなたがそれを解決したのを見ました。