Farid Rn
Farid Rn

Reputation: 3207

Sort object contents by a reference array

My question may look a little silly but I'm writing an object that outputs HTML tables from given data. The given data is a json-encoded string which contains these a header array and a data object:

for example:

{
    "header":["id","fname","lname","position"],
    "data":{
        "0":{"position":"Developer","fname":"Tom","lname":"Jones","id":12},
        "1":{"position":"UI Designer","fname":"John","lname":"Smith","id":18},
        "2":{"position":"UX Specialist","fname":"Farid","lname":"Rn","id":110}
    }
}

The problem is that the data's ordering is not the same as the header.

I want to use the header array as reference and sort each rows of data object by it. Is that possible?

Upvotes: 1

Views: 183

Answers (1)

PaulProgrammer
PaulProgrammer

Reputation: 17670

Sure! Use an external and internal loop. The external loop runs through data elements, and the internal loop runs through the header list. For each item in the header list, get it's value from the associative array in the data item.

Psuedocode:

foreach ($thing->data as $item) {
    // here would be a good place for the <tr>
    foreach ($thing->header as $header) {
        $dataforheader = $item->$header;
        // do something, maybe output a <td>
    }
}

Now, you could also put this into an alternate data structure for sorting.

Upvotes: 1

Related Questions