PHP ile filtreleme

3 Cevap php

Ben bir column1 bir $ veri bana gösterir var:

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

Ben gibi column1 beni gösterir sadece "AB" ile başlayan $ veri göstermek istiyorum:

"ABC1234" "ABD123"

diğerleri değil, aynı zamanda "ABC1234" ile ilgili diğer satırlar ve sütunlar ve "abd123"


Önceden Thanx.

Sample structure

3 Cevap

$data dizeleri bir dizi ise, kullanabilirsiniz array_filter.

PHP 5.3 veya daha yenisi:

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

PHP 5.3 öncesi:

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

Veya:

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

Ya da bir döngü kullanabilirsiniz:

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

Edit

Eğer döngü isteyeceksiniz gibi örnek kod, görünüyveya:

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;
    }
}

veya:

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);

Ben sadece aşağıdaki kod parçasında olduğu gibi, substr() kullanmak istiyorsunuz:

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

strpos (http://www.php.net/manual/en/function.strpos.php), gibi kullanın

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

"AB" bulunmazsa eğer fonksiyon kullanarak 0'a eşit, hangi return false == çünkü, === yerine == kullanımı çok emin olun .