用数组中的关联键替换数字数组键

时间:2015-01-28 14:31:02

标签: php arrays multidimensional-array

我有一个与此类似的数据集,我试图将DATA中的数字键值替换为COLUMNS中的相应值。我可以循环地做到这一点,但我不认为我能以最有效的方式做到这一点。任何人都可以提出任何我认为无法实现这一目标的好功能吗?

现有风格

stdClass Object
(
    [COLUMNS] => Array
        (
            [0] => MATCHID
            [1] => SEASON
            [2] => COMPETITION
            [3] => ROUNDID
            [4] => ROUNDSORT
            [5] => ROUNDNAME
        )

    [DATA] => Array
        (
            [0] => Array
                (
                    [0] => 141627
                    [1] => 2013/2014
                    [2] => The Scottish Cup
                    [3] => 18
                    [4] => 11
                    [5] => Final
                )

            [1] => Array
                (
                    [0] => 140895
                    [1] => 2013/2014
                    [2] => The Scottish Cup
                    [3] => 16
                    [4] => 10
                    [5] => Semi-Final
                )
        )
)

期望的风格

stdClass Object
(
    [COLUMNS] => Array
        (
            [0] => MATCHID
            [1] => SEASON
            [2] => COMPETITION
            [3] => ROUNDID
            [4] => ROUNDSORT
            [5] => ROUNDNAME
        )

    [DATA] => Array
        (
            [0] => Array
                (
                    [MATCHID] => 141627
                    [SEASON] => 2013/2014
                    [COMPETITION] => The Scottish Cup
                    [ROUNDID] => 18
                    [ROUNDSORT] => 11
                    [ROUNDNAME] => Final
                )
            [1] => Array
                (
                    [MATCHID] => 140895
                    [SEASON] => 2013/2014
                    [COMPETITION] => The Scottish Cup
                    [ROUNDID] => 16
                    [ROUNDSORT] => 10
                    [ROUNDNAME] => Semi-Final
                )
        )
)

2 个答案:

答案 0 :(得分:3)

foreach ($data->DATA as $key => $array) {
    $data->DATA[$key] = array_combine($data->COLUMNS, $array);
}

$data是您展示的对象。

循环浏览数据并将密钥与数据合并,请参阅array_combine

答案 1 :(得分:2)

$data->DATA = array_map(function (array $entry) use ($data) {
    return array_combine($data->COLUMNS, $entry);
}, $data->DATA);