0

I have an array:

$row = [
  "serial_number" => "TDZL02616"
  "id_machine" => "1720"
  "action" => "go"
]

and I have also an multidimensional array with definition of columns and their order (column 'sequence'):

$colDef = [
    [

        'name'       => 'serial_number',
        'sequence'   => 2,
        'visible'    => true,
    ],
    [
        'name'          => 'id_machine',
        'sequence'      => 1,
        'visible'       => true,
    ],
    [
        'name'     => 'action',
        'sequence' => 3,
        'visible'  => true,
    ],
]

How can I easily sort the first array ($row) according the second array ($colDef) and its columns 'sequence' that I will get the result:

$row = [
  "id_machine" => "1720"
  "serial_number" => "TDZL02616"
  "action" => "go"
]

I have no clue where to start or how to solve it.

6
  • You want $row keys in a specific order? Can I ask why? I mean, it won't affect accessing the values.. Commented Mar 15, 2017 at 12:57
  • I know, that is because I'm using array later in json response to the datatable where data (in tbody) must be in same order as header of table. Commented Mar 15, 2017 at 13:00
  • Sounds like a dangerous way of doing it. Can't you send another array along in the JSON, that contains the keys in the right order? Like ['id_machine','serial_number','go']? Edit: Taking it a step further, it should be the responsibility of the client to fetch things in the order needed. Commented Mar 15, 2017 at 13:02
  • But that is my question how to change order of keys in right sequence according definition in another array. The process is dynamic so I need at first sort array. The sequence 1. id_machine, 2. serial_number, 3. action doesn't have to be always in that order. Commented Mar 15, 2017 at 13:14
  • I understand, and I don't want to cause any trouble at all. I was just trying to highlight some possible dangers in the design :). It's a bit like SELECT * queries in SQL. Unless somehow $colDef is used in both places, then it's of course more safe. ..But in that case, if you have access to $colDef you don't have to order the keys anymore. Commented Mar 15, 2017 at 13:19

1 Answer 1

2

Try this.

$colDef2 = [];
foreach($colDef as $cd){
    $colDef2[$cd['sequence']] = $cd['name'];
}
ksort($colDef2);

$row2 = [];
foreach($colDef2 as $i){
    $row2[$i] = $row[$i];
}

Note the use of PHP function ksort which can be found here.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.