PHP:将多维数组转换为简单数组
Posted
技术标签:
【中文标题】PHP:将多维数组转换为简单数组【英文标题】:PHP: convert multidimensional array to simple array 【发布时间】:2016-02-05 04:49:12 【问题描述】:这是我在这里的第一篇文章,我目前正在从事学校的一个项目。和 我无法从 php 多维数组转换它:
Array
(
[0] => Array
(
[Program_ID] => 1001
[Program_Name] => Computer Engineering
[Program_NumHours] => 200
[Curriculum_ID] => 101
)
[1] => Array
(
[Program_ID] => 1002
[Program_Name] => Civil Engineering
[Program_NumHours] => 200
[Curriculum_ID] => 102
)
[2] => Array
(
[Program_ID] => 1003
[Program_Name] => Electronics Engineering
[Program_NumHours] => 200
[Curriculum_ID] => 103
)
[3] => Array
(
[Program_ID] => 1004
[Program_Name] => Electrical Engineering
[Program_NumHours] => 200
[Curriculum_ID] => 104
)
)
我想将该数组转换成这个:
Array
(
[0] => Array
(
[0] => 1001
[1] => Computer Engineering
[2] => 200
[3] => 101
)
[1] => Array
(
[0] => 1002
[1] => Civil Engineering
[2] => 200
[3] => 102
)
[2] => Array
(
[0] => 1003
[1] => Electronics Engineering
[2] => 200
[3] => 103
)
[3] => Array
(
[0] => 1004
[1] => Electrical Engineering
[2] => 200
[3] => 104
)
)
此数据是使用 codeigniter 从数据库中提取的。提前致谢。
【问题讨论】:
我可能是盲人,但您的预期结果与输入具有相同的结构/维数 - 只有“内部”数组中的键已更改。 是的,我只是想将关联数组转换为简单数组 见***.com/questions/15191903/… 【参考方案1】:见http://docs.php.net/array_values 和http://docs.php.net/array_map
<?php
$input = array(
array('Program_ID' => 1001, 'Program_Name' => 'Computer Engineering', 'Program_NumHours' => 200, 'Curriculum_ID' => 101),
array('Program_ID' => 1002, 'Program_Name' => 'Civil Engineering', 'Program_NumHours' => 200, 'Curriculum_ID' => 102),
array('Program_ID' => 1003, 'Program_Name' => 'Electronics Engineering', 'Program_NumHours' => 200, 'Curriculum_ID' => 103),
array('Program_ID' => 1004, 'Program_Name' => 'Electrical Engineering', 'Program_NumHours' => 200, 'Curriculum_ID' => 104),
);
$result = array_map('array_values', $input);
var_export($result);
打印
array (
0 =>
array (
0 => 1001,
1 => 'Computer Engineering',
2 => 200,
3 => 101,
),
1 =>
array (
0 => 1002,
1 => 'Civil Engineering',
2 => 200,
3 => 102,
),
2 =>
array (
0 => 1003,
1 => 'Electronics Engineering',
2 => 200,
3 => 103,
),
3 =>
array (
0 => 1004,
1 => 'Electrical Engineering',
2 => 200,
3 => 104,
),
)
【讨论】:
以上是关于PHP:将多维数组转换为简单数组的主要内容,如果未能解决你的问题,请参考以下文章
php PHP array_flatten()函数。将多维数组转换为一维数组。