Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm looking for a php function that would find array class object value 'FIND_ME' and swap it as first array key if it exists.

Here is my current Array output :

Array ( 
        [0] => stdClass Object ([id] => 1 [uid] => 52 [type] => A_TEST [title] => TITLE [value] => 1 ) 
        [1] => stdClass Object ([id] => 2 [uid] => 52 [type] => TEST [title] => TITLE [value] => 1 )
        [2] => stdClass Object ([id] => 3 [uid] => 52 [type] => FIND_ME [title] => TITLE [value] => 1 )
    )

And here is the result I need :

Array ( 
        [0] => stdClass Object ([id] => 3 [uid] => 52 [type] => FIND_ME [title] => TITLE [value] => 1 ) 
        [1] => stdClass Object ([id] => 2 [uid] => 52 [type] => TEST [title] => TITLE [value] => 1 )
        [2] => stdClass Object ([id] => 1 [uid] => 52 [type] => A_TEST [title] => TITLE [value] => 1 )
    )

Result : Array[2] changed and became Array[0] because type => FIND_ME was found in the array.

Note: I don't care about the order of others keys.

Any idea?

EDIT: Okay I managed to find the key number of type => FIND_ME using foreach() :

foreach($array as $key => $value) {
        if ($value->type == 'FIND_ME') {
            $found = $key;
            break;
        }
    }

But how to swap it as first key of the array?

share|improve this question
    
What have you tried? –  j0k Mar 3 '13 at 6:49
    
Does it matter what order the other elements are in after sorting? –  leftclickben Mar 3 '13 at 6:52
    
Nope, it doesn't matter, I just want the value 'FIND_ME' gets the key [0] –  hawkidoki Mar 3 '13 at 6:57

1 Answer 1

up vote 2 down vote accepted
$found = $others = array();
foreach($array as $key => $value) {
    if ($value->type == 'FIND_ME') {
        $found[] = $value;
    }else{
        $others[] = $value;
    }
}
$array = array_merge($found,$others);
share|improve this answer
    
Awesome! Works perfeclty. Think you ;) –  hawkidoki Mar 3 '13 at 7:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.