如何按字符串中的不同点对数组字符串进行排序

时间:2013-05-22 22:36:28

标签: php

我的结果是从脚本创建的HTML页面。

thumbnail[++nr] = new makeIt(nr, "slides/IMG_3924.html", "thumbs/IMG_3924.jpg", 150, 100, "IMG_3924.jpg", "slides/IMG_3924.jpg", 150, 100, "", "sorting01", 0)
thumbnail[++nr] = new makeIt(nr, "slides/IMG_3909.html", "thumbs/IMG_3909.jpg", 100, 150, "IMG_3909.jpg", "slides/IMG_3909.jpg", 100, 150, "", "sorting02", 0)
thumbnail[++nr] = new makeIt(nr, "slides/IMG_3914.html", "thumbs/IMG_3914.jpg", 150, 100, "IMG_3914.jpg", "slides/IMG_3914.jpg", 150, 100, "", "sorting02", 0)
thumbnail[++nr] = new makeIt(nr, "slides/IMG_3904.html", "thumbs/IMG_3904.jpg", 100, 150, "IMG_3904.jpg", "slides/IMG_3904.jpg", 100, 150, "", "sorting01", 0)

这是产生它的代码

if ($file2 != "." && $file2 != ".." && strpos($file2,'.')!==0 ) {
  list($widthT2, $heightT2, $type2, $attr2) = getimagesize($pathToThumbs."/$name2.jpg"); 
  $thumbW2 = $widthT2;
  $thumbH2 = $heightT2;
  $out[]="thumbnail[++nr] = new makeIt(nr, \"slides/$name2.html\", \"thumbs/$name2.jpg\", $thumbW2, $thumbH2, \"$name2.jpg\", \"slides/$name2.jpg\", $widthT2, $heightT2, \"\", \"$commentaire\", 0)\n";
}

}

//usort($out, function ($a, $b){
//    return substr($b, -8) - substr($a, -8);
//});
sort($out);

foreach($out as $key => $value){
  print $value;
}

如何对结果进行排序,使其按sorting01排序,然后按每行末尾的sorting02文字排序?我想根据每行的最后两个字段对数组进行排序。

1 个答案:

答案 0 :(得分:0)

在字符串中搜索最后"some text in quotas"并进行比较:

function compare($a,$b) 
{
    // searching commentaire (searching last " and second from end ")

    $end_commentaire = strrpos($a, '"');
    $substr_a = substr($a, 0, $end_commentaire);
    $begin_commentaire = strrpos($substr_a, '"');   
    $substr_a = substr($substr_a, $begin_commentaire+1);

    $end_commentaire = strrpos($b, '"');
    $substr_b = substr($b, 0, $end_commentaire);
    $begin_commentaire = strrpos($substr_b, '"');   
    $substr_b = substr($substr_b, $begin_commentaire+1);

    //echo "|$substr_a|$substr_b|<br>";

    // compare 

    $result = strcmp($substr_a, $substr_b);

    // $substr_a and $substr_b are different,
    // don't compare rest of string 

    if( $result != 0 )
         return $result;

    // $substr_a and $substr_b are the same,
    // compare rest of string 

    return strcmp($a, $b);
}

usort($out, 'compare');

将其替换为sort($out)

修改

使用RegEx:

function compare($a,$b) 
{
    // searching commentaire (searching last " and second from end ")

    preg_match('/"([^"]*)"[^"]*$/', $a, $result_a);
    preg_match('/"([^"]*)"[^"]*$/', $b, $result_b);

    //echo "|$result_a[1]|$result_b[1]|$result_a[0]|$result_b[0]|<br>";

    // compare 

    $result =  strcmp($result_a[1], $result_b[1]);

    // $result_a[1] and $result_b[1] are different,
    // don't compare rest of string 

    if( $result != 0 )
         return $result;

    // $result_a[1] and $result_b[1] are the same,
    // compare rest of string 

    return strcmp($a, $b);
}

usort($out, 'compare');