获取所有数组条目的键,用下划线字符(_)分割它们,然后将它们放入一个数组中。
$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 中是不可能的。
编辑:我看到你解决了。