我怎么能在PHP中过滤这个数组?

时间:2014-12-29 15:44:52

标签: php

我有以下数组。我想区分数组

[role_code] => Array
        (
            [0] => Array
                (
                    [16] => CA
                )

            [1] => Array
                (
                    [16] => TA
                )

            [2] => Array
                (
                    [16] => GA
                )

            [3] => Array
                (
                    [17] => CA
                )

            [4] => Array
                (
                    [17] => GA
                )
    )

我怎样才能得到这个数组如下

Array
(
    [16] => Array
        (
            [0] => CA
            [1] => TA
            [2] => TA

        )

    [17] => Array
        (
            [0] => TA
            [1] => GA
        ) 

)

我已经完成了以下代码但它得到了这个数组

Array
(
    [16] => CA
)
Array
(
    [16] => TA
)
Array
(
    [16] => GA
)
Array
(
    [17] => CA
)
Array
(
    [17] => GA
)

3 个答案:

答案 0 :(得分:4)

参见在线示例here

<?php
//your array
$array = [
    [16 => 'CA'],
    [16 => 'TA'],
    [16 => 'GA'],
    [17 => 'CA'],
    [17 => 'GA']
];

//variable to result
$result = [];

foreach ($array as $value) {
    foreach ($value as $k => $v) {
        $result[$k][] = $v;
    }
}

答案 1 :(得分:0)

通过简单的循环完成工作。

$newArray = array();
foreach ($role_code as $subarray) {
    foreach ($subarray as $key => $val) {
            $newArray[$key][] = $val;
    }
}
var_dump($newArray);

答案 2 :(得分:0)

$array = array(
'role_code' => Array(0 => Array(16 => 'CA'),1 => Array(16 => 'TA'), 2 => Array(16 => 'GA'),3 => Array(17 => 'CA'),4 => Array(17 => 'GA')));
foreach($array[role_code] as $key=>$smallArray)
{
    foreach($smallArray as $keySmallArray=>$value){
        $newArray[$keySmallArray][] = $value;
    }
}
print_r("<pre>");
print_r($newArray);
print_r("</pre>");