2013-07-18 85 views
-2

在php ....我怎樣才能排序下面的例子,通過「attachment_id」下每個單個數組[圖像] [videoembed] [etc]因此,[圖像]將訂購691,692,699,然後[videembed]會被類似的命令,如果有超過1 ...等等。php - 按子對象排序數組

我真的希望這是有道理的。

非常感謝大家。

(
    [image] => Array 
    (
     [0] => stdClass Object 
      (
       [title] => 77007_433592946695465_6701985_n.jpg      
       [attachment_id] => 699 
      ) 

     [1] => stdClass Object 
      (
       [title] => 253163_10151127010009522_736212653_n.jpg 
       [attachment_id] => 692 
      ) 

     [2] => stdClass Object 
      (
       [title] => 263893_10150217397944522_4550001_n.jpg 
       [attachment_id] => 691 
      ) 

    ) 

[videoembed] => Array 
    (
     [0] => stdClass Object 
      (     
       [title] => YouTube 
       [attachment_id] => 692 
      ) 

    ) 

[] => Array 
    (
     [0] => stdClass Object 
      (
       [title] => yada.jpg      
       [attachment_id] => 688 
      ) 

    ) 

) 

回答

1

您可以使用並給出自定義比較函數。

+0

這事我想,但不能得到它的工作: 代碼: 功能CMP($ A,$ B){ \t \t回報$ A- > attachment_id - $ b-> attachment_id; \t \t} $ a \t = $ p-> get_attached_array(); \t \t $ newarray = array(); \t \t \t \t \t 的foreach \t($ a作爲attach_type $){// $ attach_type =子陣列的主陣列($ A)...圖像陣列,vieoembed陣列等 \t \t \t $ newarray [] = usort($ attach_type,'cmp'); \t \t} \t \t \t \t的print_r($ newarray); –

+0

我不確定我是否正確理解你的問題,但是如果你想讓你的數組首先被「類型」(圖像,videoembed)和附件id排序,那麼首先你需要使用usort排序子數組,然後連接它們並按鍵(ksort)排序。我不確定它可以用一種方式完成,但也許有一些全局狀態的扭曲的usort可以做到這一點。 – erdeszt

1

使用usort如下:

function cmp($a, $b) { 
    if( $a->attachment_id == $b->attachment_id){ return 0 ; } 
    return ($a->attachment_id< $b->attachment_id) ? -1 : 1; 
} 

for($i=0, $i<len($imagearray), $i++) 
{ 
    usort($imagearray,'cmp');//assign image array to $imagearray 
} 
+0

[image]是父數組的子數組。所以它是: mainarray-> image array-> objects-> attachment_id mainarray-> videoembed array-> objects-> attachment_id 所以想要通過附件id對mainarray-> image數組下的所有對象進行排序,對於videoembed也是一樣的數組等,同時保持它們在mainarray ..如果這是有道理的。 –

+0

你可以試試我上面給出的代碼沒有經過測試。我直接寫在這裏。請通知有效的代碼。 –

+0

這是我試過的,類似的,但不能得到它的工作: $ a = $ p-> get_attached_array(); (我們在這裏獲得數組) \t \t $ newarray = array(); \t \t \t 功能\t CMP($一個,$ B){ \t \t返回($ A-> attachment_id < $b-> attachment_id)? -1:1; \t \t} \t \t的foreach($ a作爲$ attach_type){ \t \t \t $ newarray [] = usort($ attach_type, 'CMP'); \t \t} \t \t \t \t的print_r($ newarray); –