2012-01-06 18 views
1

我一直在为最近几个小时试图找到这个解决方案。带上一个具有自定义值的密钥 - 多维数组

我有这样的多维数组:

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结果是第一个。

我尝试过在网上找到不同的片段,但找不到能帮助我的片段。

回答

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"); 
+0

@SergeS首先得到正确答案。 usort是要走的路。 – davidethell 2012-01-06 11:24:26

+0

非常感谢! – MariusH 2012-01-08 18:01:42