PHP多维数组分解

我有一个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)
    )

解决方法:

将您的源数组名称视为$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);
上一篇:使用MySQL查询选择多个和,并将它们显示在单独的列中


下一篇:python – Pandas:pivot和pivot_table之间的区别.为什么只有pivot_table工作?