查找数组类对象值 - 如果存在:将其作为第一个数组键移动

时间:2013-03-03 06:46:03

标签: php arrays sorting object

我正在寻找一个可以找到数组类对象值'FIND_ME'的php函数,并将其作为第一个数组键交换(如果存在)。

这是我当前的数组输出:

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

这是我需要的结果:

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

结果:数组[2]已更改并变为数组[0],因为在数组中找到了type => FIND_ME

注意:我不关心其他键的顺序。

有什么想法吗?

编辑:好的,我设法使用foreach()找到了type => FIND_ME的密钥编号:

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

但是如何将它作为数组的第一个键交换?

1 个答案:

答案 0 :(得分:2)

$found = $others = array();
foreach($array as $key => $value) {
    if ($value->type == 'FIND_ME') {
        $found[] = $value;
    }else{
        $others[] = $value;
    }
}
$array = array_merge($found,$others);