带来一个具有自定义值的键 - 多维数组

时间:2012-01-06 11:14:56

标签: php arrays multidimensional-array

在过去的几个小时里,我一直在努力寻找解决方案。

我有这个多维数组:

Array
(
    [0] => stdClass Object
        (
            [id] => 128
            [itemID] => 27
            [attribute] => xxx
        )

    [1] => stdClass Object
        (
            [id] => 129
            [itemID] => 27
            [attribute] => xxx
        )

    [2] => stdClass Object
        (
            [id] => 130
            [itemID] => 27
            [attribute] => xxx
        )

    [3] => stdClass Object
        (
            [id] => 131
            [itemID] => 27
            [attribute] => xxx
        )

    [4] => stdClass Object
        (
            [id] => 132
            [itemID] => 27
            [attribute] => xxx
        )

    [5] => stdClass Object
        (
            [id] => 133
            [itemID] => 27
            [attribute] => yyy
        )

    [6] => stdClass Object
        (
            [id] => 134
            [itemID] => 27
            [attribute] => xxx
        )

)

你可以看到obj。 5具有'yyy'的属性键。 我想把这个包含'yyy'属​​性键的对象带到前面,就像重新排序一样,所以当我foreach时,yyy结果是第一个。

我尝试过使用网上找到的不同片段但找不到帮助我的片段。

2 个答案:

答案 0 :(得分:1)

鉴于上面的数组:

function sortMyArray($item1, $item2) {
    $result = 0;
    if ($item1->attribute == 'yyy') {
        $result = -1;
    }
    else if ($item2->attribute == 'yyy') {
        $result = 1;
    }
    return $result;
}

usort($yourArray, "sortMyArray");

答案 1 :(得分:0)

看到这个 - http://www.php.net/manual/en/function.usort.php,可以帮到你

所以对你的数组进行排序,并使用自定义函数,比较if属性是否合适(并将yyy作为$ a返回-1,将yyy作为$ b返回1,否则返回0)