在php中重组数组
我有以下源数组,我正在尝试使用 group_name 对其进行重组,以提供下面的所需输出。
任何帮助或指示表示赞赏。 谢谢,Lk
来源:
Array
(
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
输出:
Array
(
[group_other] => Array
(
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
)
[group_web_links] => Array
(
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
)
I have the following source array which I'm trying to restructure using group_name to give me the require output below.
Any help or pointers appreciated.
Thanks, Lk
Source:
Array
(
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
Output:
Array
(
[group_other] => Array
(
[field_b] => Array
(
[type] => number_integer
[group_name] => group_other
)
)
[group_web_links] => Array
(
[field_d] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_e] => Array
(
[type] => link
[group_name] => group_web_links
)
[field_f] => Array
(
[type] => text
[group_name] => group_web_links
)
)
[field_a] => Array
(
[type] => text
[group_name] =>
)
[field_c] => Array
(
[type] => text
[group_name] =>
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可以通过一个简单的
foreach
循环来完成:This can be accomplished by a simple
foreach
loop:如果新数组的键顺序不是那么重要:
If key order of new array is not so important:
像这样的东西:
Something like this:
我想那些对此投反对票的人正在这样做,因为我没有初始化 $new_array[ $field[ 'group_name' ] ]。好吧,这在 PHP 中不是必需的,当您执行
$new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
时,它将自动用空数组初始化。I suppose those who are down voting this are doing it because I am not initializing
$new_array[ $field[ 'group_name' ] ]
. Well, that is not necessary in PHP, it will be automatically initialized with an empty array when you do$new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
.