在 PHP 中从现有多维数组创建多维数组
在 PHP 中,可以基于现有数组创建新的多维数组。以下是如何完成您在问题中描述的特定转换:
将以下 2D 数组:
$MainArray = array( [ 'Job_Name' => 'WXYZ', 'Quantity' => 1000, 'Machine_Name' => 'Machine1', 'Start_Date' => '2014-07-30 00:00:00', 'Completion_Date' => '2014-08-02 00:00:00', 'Labor' => 4 ], [ 'Job_Name' => 'ABCD', 'Quantity' => 1500, 'Machine_Name' => 'Machine2', 'Start_Date' => '2014-08-08 00:00:00', 'Completion_Date' => '2014-08-14 00:00:00', 'Labor' => 2 ], [ 'Job_Name' => 'BCDA', 'Quantity' => 1200, 'Machine_Name' => 'Machine1', 'Start_Date' => '2014-08-02 00:00:00', 'Completion_Date' => '2014-08-07 00:00:00', 'Labor' => 1 ] );
转换为以下 3D 数组:
$ConvertedArray = array( 'Machine1' => array( [ 'Job_Name' => 'WXYZ', 'Quantity' => 1000, 'Start_Date' => '2014-07-30 00:00:00', 'Completion_Date' => '2014-08-02 00:00:00', 'Labor' => 4 ], [ 'Job_Name' => 'BCDA', 'Quantity' => 1200, 'Start_Date' => '2014-08-02 00:00:00', 'Completion_Date' => '2014-08-07 00:00:00', 'Labor' => 1 ] ), 'Machine2' => array( [ 'Job_Name' => 'ABCD', 'Quantity' => 1500, 'Machine_Name' => 'Machine2', 'Start_Date' => '2014-08-08 00:00:00', 'Completion_Date' => '2014-08-14 00:00:00', 'Labor' => 2 ] ) );
解决方案:
使用以下PHP code:
$result = []; foreach($MainArray as $record){ $result[$record['Machine_Name']][] = $record; }
代码迭代 $MainArray 并针对每条记录,将其添加到 $result 数组,使用 'Machine_Name' 键的值作为索引。这将创建所需的 3D 阵列。
以上是如何根据键的值将 2D PHP 数组转换为 3D 数组?的详细内容。更多信息请关注PHP中文网其他相关文章!