PHP多维数组分解

时间:2013-01-23 05:53:37

标签: php pivot

我有一个PHP Sql结果,表格如下:

显示为:

[id]|test1|data|voice
1|0|0|-1
2|0|1|0
3|0|-2|-1

数组的Print_r如下所示:


Array
(
[2] => Array
    (
        [0] => Array
            (
                [test1] => 0
                [data] => 0
                [mobile] => -1
            )

    )

[3] => Array
    (
        [0] => Array
            (
                [test1] => 0
                [data] => 1
                [voice] => 0
            )

    )

[4] => Array
    (
        [0] => Array
            (
                [test1] => 0
                [data] => -2
                [voice] => -1
            )

    )

我想操纵数组,使我的数组看起来像:

Array (
    [0] => Array
    ( 
            [name] =>  test1
            [val] => array(0 , 0, 0) 
    )
    [1] => Array 
    (
            [name] => data
            [val] => array(0, 1, -2)
    )
    [2] => Array
    (
            [name] => voice
            [val] => array(-1,0, 0)
    )

2 个答案:

答案 0 :(得分:1)

将您的源数组名称视为$ Arr,请尝试以下代码

foreach($Arr as $valArr)
{
    $index = 0;
    foreach($valArr[0] as $k => $v)
    {
        $newArr[$index]["name"] = $k;
        $newArr[$index]["val"][ ] = $v;
        $index++;
    }
}

echo "<pre>"; print_r($newArr);

答案 1 :(得分:0)

使用此功能并在需要时进行修改

SELECT *
FROM `table_name`
GROUP BY `test1` , `data` , `voice`
LIMIT 0 , 30