2013-07-18 86 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); –