1

I have a dataset similar to this in which I am trying to replace the numeric key values within DATA to the corresponding values in COLUMNS. I can do this in a loop but I don't think I'm doing it in the most efficient way possible. Can anyone suggest any nice functions that I haven't considered to accomplish this?

Existing Style

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
                )
        )
)

Desired Style

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 Answers 2

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

$data is the object you showed.

Loop trough the data and combine the keys with the data, see array_combine

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.