开发者

Filtering by PHP

I have a $data at a column1 shows me:

"AAA123" "ABC1234" "ABD123" "BAC12" "CAB123" "DA125" and so on..

I would like to show $data starting with only "AB" which shows me at column1 like :

"ABC1234" "ABD123"

not the others but also other rows and columns related to "AB开发者_运维技巧C1234" and "ABD123"


Thanx in advance.

Sample structure http://img706.imageshack.us/img706/8994/34310422.jpg


If $data is an array of strings, you can use array_filter.

PHP 5.3 or later:

$AB = array_filter($data, function($str) {
    return 'AB' == substr($str, 0, 2);
});

before PHP 5.3:

$AB = array_filter($data, 
                   create_function('$str', 
                                   'return "AB" == substr($str, 0, 2);'
                  )               );

Or:

function create_prefix_tester($prefix) {
    return create_function('$str', 
                  "return '$prefix' == substr(\$str, 0, " . strlen($prefix) . ');'
                  );
}
$AB = array_filter($data, create_prefix_tester('AB'));

Or you could use a loop:

foreach ($data as $str) {
    if ('AB' ==  substr($str, 0, 2)) {
      // do stuff
      ...
    }
}

Edit

From the sample code, it looks like you'll want the loop:

while (FALSE !== ($line = fgets($fp))) {
    $row = explode('|', $line); // split() is deprecated
    if ('AB' == substr($row[0], 0, 2)) {
        switch($sortby) {
        case 'schools': // fallthru
        default:
            $sortValue = $row[0];
            break;
        case 'dates':
            $sortValue = $row[1];
            break;
        case 'times':
            $sortValue = $row[2];
            break;
        }
        array_unshift($row, $sortValue);
        $table[] = $row;
    }
}

or:

function cmp_schools($a, $b) {
    return strcmp($a[0], $b[0]);
}
function cmp_dates($a, $b) {
    return $a['datestamp'] - $b['datestamp'];
}
function cmp_times($a, $b) {
    return $a['timestamp'] - $b['timestamp'];
}
while (FALSE !== ($line = fgets($fp))) {
    $row = explode('|', $line); // split() is deprecated
    if ('AB' == substr($row[0], 0, 2)) {
        $when = strtotime($row[1] + ' ' + $row[2]);
        $row['timestamp'] = $when % (60*60*24);
        $row['datestamp'] = $when - $row['timestamp'];
        $table[] = $row;
    }
}
usort($table, 'cmp_' + $sortby);


I would simply use substr(), as in the following snippet:

if (substr($str, 0, 2) == 'AB') {
  // The string is right.
}


Use strpos (http://www.php.net/manual/en/function.strpos.php), like

if (strpos($my_string, "AB") === 0) {
  <do stuff>
}

Be very sure to use === instead of ==, because if "AB" is not found then the function will return false, which will equate to 0 using ==.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜