格式化多维数组PHP

时间:2015-04-12 01:55:30

标签: php arrays cakephp

我正在使用CakePHP做一个项目,我需要一个多维数组来转换带有json_encode()的JSON。我的问题是结果不是从零开始。

Array
(
[1] => Array
    (
        [0] => Array
            (
                [nombre] => Steve Jobs
                [rol] => 6
            )

        [1] => Array
            (
                [nombre] => Bill Gates
                [rol] => 8
            )

    )

[3] => Array
    (
        [2] => Array
            (
                [nombre] => Bill Gates
                [rol] => 6
            )

    )

[4] => Array
    (
        [3] => Array
            (
                [nombre] => Bill Gates
                [rol] => 6
            )

    )

)

生成该数组的代码是:

foreach ($docentes_secciones as $i => $itm):
    $j = $itm->seccion_id;
    $docentesSecciones[$j][$i]['nombre'] = $nombrePersona[$itm->perfil_id];
    $docentesSecciones[$j][$i]['rol'] = $itm->rol_id;

endforeach;

我希望我的数组采用这种格式

Array
(
[1] => Array
    (
        [0] => Array
            (
                [nombre] => Steve Jobs
                [rol] => 6
            )

        [1] => Array
            (
                [nombre] => Bill Gates
                [rol] => 8
            )

    )

[3] => Array
    (
        [0] => Array
            (
                [nombre] => Bill Gates
                [rol] => 6
            )

    )

)

如何以最后一种格式获取数组?

编辑:

$i_aux = 1;
$j = 0;
foreach ($docentes_secciones as $itm):
    $i = $itm->seccion_id;
    if($i_aux != $i)
        $j = 0;

    $docentesSecciones[$i][$j]['nombre'] = $nombrePersona[$itm->perfil_id];
    $docentesSecciones[$i][$j]['rol'] = $itm->rol_id;
    if($i_aux == $i)
        $j++;
    $i_aux = $i;

endforeach;

这对我有用,但我想提高效率。

1 个答案:

答案 0 :(得分:0)

事情是:它不是从零开始,因为在foreach中你用表的id设置$ j的值,不是吗? 我不认为你的表ID从零开始吧? 您可以尝试使用两个for循环而不是foreach。也许是这样的:

for ($i = 0; $i < count($docentes_secciones); $i++){
     for ($j = 0; $j < count($docuentes_secciones[$i]); $j++){
         $docentesSecciones[$i][$j]['nombre'] = $nombrePersona[$i]['perfil_id'];
         $docentesSecciones[$i][$j]['rol'] = [$i]['rol_id'];
     }
}