1

I have a problem in php, i tried searching but i only got more confused. I need to sort an array according to another array using the "priority" key value.

This is the order i need it filtered with.

$custom_order = array(
    array('priority' => 0, 'field_id' => 'password'),
    array('priority' => 1, 'field_id' => 'username')
);

And this is the array that needs to be filtered

$default_order = array(
    'name' => array(
        'username' => array(
            'type'        => 'text',
            'priority'    => 0
        ),
        'password' => array(
            'type'        => 'password',
            'priority'    => 1
        ),
    ),
);

And this is the order that i would like to get

$final_order = array(
    'name' => array(
       'password' => array(
            'type'        => 'password',
            'priority'    => 0
        ),
        'username' => array(
            'type'        => 'text',
            'priority'    => 1
        ),
    ),
);

I'm confused, i'm not sure whether i should use uasort, or array_intersect, by reading other articles about it i got more confused. Can anybody please explain how would i go to sort the array in this way?

Thank you so much.

alex05
  • 15
  • 3

1 Answers1

2

If priority is the actual sort criteria, then usort would be an easy way:

usort( $array['name'], function($a, $b) {
    return ($a->priority < $b->priority) ? -1 : 1;
});

This just compares the value of priority between elements of the array. If not, perhaps you could enhance your example to show how the sort should actually be determined.

EDIT: Based on the clarified question.

Because of the structure of your arrays, I don't believe that you will be able to just use PHP functions.

First, arrange the priorities in a form better for prioritzing:

$priorities = array();
foreach ($custom_order as $item) {
    $priorities[$item->field_id] = $item->priority;
}

Then assign updated priorities to the $default items:

$final_order = array();
foreach ($default_order as $item) {
    $item->priority = $priorities[$item->type];
}

Then do the sort originally suggested to get them in priority order:

usort( $final_order['name'], function($a, $b) {
    return ($a->priority < $b->priority) ? -1 : 1;
});
  • Sorry maybe i've explained myself badly. I've updated my question with a more appropriate example. Yes, "priority" is the comparison value i'd like to use. I want $default_order to be sorted based on the "priority" set into $custom_order – alex05 Mar 05 '15 at 18:38