对多维数组排序并保留兄弟数组



如何按type排序以下数组,其中url首先出现,然后是doc然后是page ?

$array = array(
    0 => array(
        'id' => '14',
        'position' => '0',
        'type' => 'related-url'
    ),
    1 => array(
        'id' => '2367',
        'position' => '0',
        'type' => 'related-doc'
    ),
    2 => array(
        'id' => '99',
        'position' => '0',
        'type' => 'related-page'
    ),
    4 => array(
        'id' => '180',
        'position' => '2',
        'type' => 'related-doc'
    ),
    5 => array(
        'id' => '10',
        'position' => '3',
        'type' => 'related-doc'
    )
);

结果是

$array = array(
    0 => array(
        'id' => '14',
        'position' => '0',
        'type' => 'related-url'
    ),
    1 => array(
        'id' => '2367',
        'position' => '0',
        'type' => 'related-doc'
    ),
    4 => array(
        'id' => '180',
        'position' => '2',
        'type' => 'related-doc'
    ),
    5 => array(
        'id' => '10',
        'position' => '3',
        'type' => 'related-doc'
    ),
    2 => array(
        'id' => '99',
        'position' => '0',
        'type' => 'related-page'
    )
);

维护键关联不重要

好吧,这是丑陋的,但它工作)

$doc = array();
$url = array();
$page = array();
foreach($array as $v)
    switch($v['type']){
        case 'related-url': $url[] = $v;break;
        case 'related-doc': $doc[] = $v;break;
        case 'related-page': $page[] = $v;break;
    }
$array = array_merge($url, $doc, $page);

好了

function cmp($a, $b) {
    $v1 = $a['type'];
    $v2 = $b['type'];   
    $v1 = str_replace("related-", "", $v1);
    $v2 = str_replace("related-", "", $v2); 
    $firstChar = abs(ord(substr($v1,0,1)) - ord("u"));
    $firstChar2 = abs(ord(substr($v2,0,1)) - ord("u"));
    return $firstChar<=$firstChar2?-1:1; 
}
usort ( $array, "cmp" );
function cmp($a, $b) {
    $sortOrder = array(
        "related-url"   => 1,
        "related-doc"   => 2,
        "related-page"  => 3
    );
    return $sortOrder[$a['type']] - $sortOrder[$b['type']];
}
usort($array, "cmp");

使用ussort,这里有一个简单的例子。我很确定这个逻辑是有效的,但毫无疑问有更好的方法。

usort($your_array, function ($elem1, $elem2) {
  if($elem1['type'] == 'related-url')
    return true;
  elseif($elem2['type'] == 'related-url' )
    return false;
  elseif($elem1['type'] == 'related-doc')
    return true;
  else
    return false;
});

如果element1是一个url,它总是返回true,如果它不是并且element2是一个url,它总是返回false。如果这两个语句都不为真,并且element1为doc,则返回true,因为element2为doc或page。最后,如果element1是页面,则总是返回false,因为element2是文档或页面。

应该可以了

$urls = $docs = $pages = array();
foreach ($array as $sub) {
    switch($sub['type']) {
        case 'related-url':
            $urls[] = $sub;
        break;
        case 'related-doc':
            $docs[] = $sub;
        break;
        case 'related-page':
            $pages[] = $sub;
        break;
   }
}
$result = array_merge($urls, $docs, $pages);
echo '<pre>', var_dump($result), '</pre>';

相关内容

  • 没有找到相关文章

最新更新