PHP-按字母顺序过滤数组字符串

时间:2018-11-22 12:07:32

标签: php arrays filter

我有一个字符串数组

form

我想检索所有字母以字母A,B,C等等开头的所有字符串。

避免无用代码重复的最佳方法是什么?

5 个答案:

答案 0 :(得分:2)

您可以创建一个以第一个字母为索引的临时多维数组。试试-

$cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];

foreach($cities as $city) {
    $first = substr($city, 0, 1);
    $temp_cities[$first][] = $city;
}

var_dump($temp_cities);

输出

array(8) {
  ["N"]=>
  array(1) {
    [0]=>
    string(8) "New York"
  }
  ["B"]=>
  array(1) {
    [0]=>
    string(6) "Boston"
  }
  ["L"]=>
  array(1) {
    [0]=>
    string(11) "Los Angeles"
  }
  ["C"]=>
  array(2) {
    [0]=>
    string(10) "Cincinnati"
    [1]=>
    string(7) "Chicago"
  }
  ["H"]=>
  array(1) {
    [0]=>
    string(7) "Houston"
  }
  ["P"]=>
  array(1) {
    [0]=>
    string(12) "Philadelphia"
  }
  ["D"]=>
  array(1) {
    [0]=>
    string(6) "Dallas"
  }
  ["S"]=>
  array(1) {
    [0]=>
    string(7) "Seattle"
  }
}

要查找以'C'开头的城市-var_dump($temp_cities['C'])

答案 1 :(得分:0)

usort($cities, function($a, $b){
    return $a <=> $b;
});

答案 2 :(得分:0)

请尝试这个

<?php

$cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];
$new_array = [];
$search_string = 'C'; // Letter to search
foreach ($cities as $city) {
    if (strpos($city, $search_string) === 0) {
        $new_array[] = $city;
    }
}
print_r($new_array);// New array will contian list of identified cities
?>

答案 3 :(得分:0)

您可以简单地使用

对数组进行排序
$cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];

sort($cities);

答案 4 :(得分:0)

如果我理解正确,您正在尝试创建26个数组,每个字母对应一个字母,每个数组包含以该字母开头的城市。

<?php
    $cities = ['New York', 'Boston', 'Los Angeles', 'Cincinnati', 'Chicago', 'Houston', 'Philadelphia', 'Dallas', 'Seattle'];

    //Our 26 arrays
    $arrA = array();
    $arrB = array();
    $arrC = array();
    $arrD = array();
    $arrE = array();
    $arrF = array();
    $arrG = array();
    $arrH = array();
    $arrI = array();
    $arrJ = array();
    $arrK = array();
    $arrL = array();
    $arrM = array();
    $arrN = array();
    $arrO = array();
    $arrP = array();
    $arrQ = array();
    $arrR = array();
    $arrS = array();
    $arrT = array();
    $arrU = array();
    $arrV = array();
    $arrW = array();
    $arrX = array();
    $arrY = array();
    $arrZ = array();

    //Fill the array for that city.
    foreach ($cities as $city){
        $key = substr($city, 0, 1);
        ${"arr".$key}[] = $city;
    }
    //Let's just test this worked.
    var_dump($arrC);
    var_dump($arrB);
    var_dump($arrN);

?>