0

I have this complex array that I need to sort by value that is deep inside the array.

here's the array structure:

$array = array(
    array(
        'data' => array(
              'tree_id'   => 0,
              'title_tag' => 'Annex A',
        ),
        'nodes' => array(
             array(
                 array(
                     'data'  => array(
                          'tree_id' => 0,
                          'title_tag' => 'Annex A'
                     ),
                     'attachments' => array(
                          'title_tag' => 'Annex A',
                          'updated_by' => 'Steve'
                     )
                 ) 
             ),
             array(
                 array(
                      'data'  => array(
                      'tree_id' => 0,
                      'title_tag' => 'Annex B'
                 ),
                 'attachments'   => array(
                     'title_tag' => 'Annex B',
                     'updated_by'  => 'Steve'
                 )
              )
          )
      )
   )
);

I would like to sort the $array[ array[nodes][array][array][data]['title_tag'] ] alphabetically.

Here's what I've done so far:

foreach( $array as $arr ){
    foreach( $arr['nodes'] as $node ){
        foreach( $node as $data ){
            $keys[] = $data['data']['title_tag'];
        }
        array_multisort($keys,SORT_DESC,$node);
    }

}

4

1 回答 1

0

您可以使用用户定义的排序...

function my_array_sort($a, $b) {

    // compare the 2 elements
    return strnatcmp ( $a[0][data]['title_tag'], $b[0][data]['title_tag'] );

}

foreach( $array as $arr ) {

    uasort($arr['nodes'], "my_array_sort");

}

但认真的人,我建议创建一个作为“节点”对象的类。它将使您的代码更易于使用并允许具有明确的结构,而无需记住每个键名。

您也不需要在数组对象中将每个节点包装两次。这将做同样的事情......

'nodes' => array(
              array(
                  'data'  => array(
                       'tree_id' => 0,
                       'title_tag' => 'Annex A'
                  ),
                  'attachments' => array(
                       'title_tag' => 'Annex A',
                       'updated_by' => 'Steve'
                  )
              ),
              array(
                  'data'  => array(
                      'tree_id' => 0,
                      'title_tag' => 'Annex B'
                 ),
                 'attachments'   => array(
                      'title_tag' => 'Annex B',
                      'updated_by'  => 'Steve'
                 )
              )
           );
于 2013-05-23T15:30:34.577 回答