php拆分多维数组

时间:2014-10-15 17:07:37

标签: php arrays multidimensional-array

我有以下数组:

Array (

    [0] => Array (
        [nombre] => Juan Mandrola
        [id] => 5
        [fecha_egreso] => 15/10/2014
        [hora_egreso] => 15:00
    )

    [1] => Array (
        [nombre] => Pedro Martinez
        [id] => 5
        [fecha_egreso] => 17/10/2014
        [hora_egreso] => 15:00
    )

)

我需要将第一个数组分成2个数组,更改“mecanico”元素“nombre”和另一个名为“tarea”的数组中的其他元素。

Array (

    [0] => Array (
        [mecanico] => Juan Mandrola
        [tarea] => Array (
                [id] => 1
                [fecha_egreso] => 15/10/2014
                [hora_egreso] => 15:00
            )

    )

    [1] => Array (
        [mecanico] => Pedro Martinez
        [tarea] => Array (
                [id] => 5
                [fecha_egreso] => 17/10/2014
                [hora_egreso] => 15:00
            )

    )

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:0)

$newArray = array();
foreach($array as $key=>$val){
 $newArray[]['tarea'] = array('id'=>$val['id'], 'fecha_egreso'=>$val['fecha_egreso'], 'hora_egreso'=>$val['egreso']);
 $newArray[]['mecanico'] = $val['nombre'];
}

答案 1 :(得分:0)

快速而肮脏的解决方案是创建一个新数组并根据需要分配值。虽然这不是最好的做事方式,但这里有伪代码:

for($i = 0; $i < count($myOldArray); $i++) {
  $myNewArray[$i]['mecanico']    = $myOldArray[$i]['nombre'];
  $myNewArray[$i]['tarea']['id'] = $myOldArray[$i]['id'];
  $myNewArray[$i]['tarea']['fecha_egreso'] = $myOldArray[$i]['fecha_egreso'];
  $myNewArray[$i]['tarea']['hora_egreso']  = $myOldArray[$i]['hora_egreso'];
}