1

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

这是我当前的数组输出:

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

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

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

任何想法?

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

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

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

4

1 回答 1

2
$found = $others = array();
foreach($array as $key => $value) {
    if ($value->type == 'FIND_ME') {
        $found[] = $value;
    }else{
        $others[] = $value;
    }
}
$array = array_merge($found,$others);
于 2013-03-03T07:18:51.167 回答