【问题标题】:How to search for the index of a string in a 2 dimensional array如何在二维数组中搜索字符串的索引
【发布时间】:2017-08-16 04:33:37
【问题描述】:

我需要在下面的数组中找到一个字符串被分解后的索引。所以在这个例子中,我需要找到“真的”的索引。我该怎么做?

function explode2D($row_delim, $col_delim, $str) {
        return array_map(function ($line) use ($col_delim) {
            return explode($col_delim, $line);
        }, explode($row_delim, $str));
    } // - slick coding by trincot


$string = 'red<~>blue<~>orange[|]yellow<~>purple<~>green[|]really<~>dark<~>brown';

$array = explode2D("[|]", "<~>", $string);

返回

Array
(
    [0] => Array
        (
            [0] => red
            [1] => blue
            [2] => orange
        )

    [1] => Array
        (
            [0] => yellow
            [1] => purple
            [2] => green
        )

    [2] => Array
        (
            [0] => really
            [1] => dark
            [2] => brown
        )

)

所以我尝试了这个

$search = 'really';

$index = array_search($search, $array);

print($index);

什么都没有:(

【问题讨论】:

标签: php arrays string search indexing


【解决方案1】:

array_search 不起作用,因为您要在 arrays 的数组中查找字符串。您需要遍历外部数组和 array_search 该数组内的每个集合。

foreach ($array as $key => $set) {
    $index = array_search($search, $set);
    if (false !== $index) {
        echo "Found '$search' at index $index of set $key";
        break;
    }
}

我不确定您要查找哪个索引,因为使用这样的结构,有两个索引指示您的搜索字符串在哪里,一个用于外部数组,一个用于内部数组。但是如果你在找到$search 之后打破循环,那么$key 将是此时外部数组的正确索引,所以你将拥有它们。

【讨论】:

    【解决方案2】:
    for ($i = 0; $i < count($array); $i++) {
        if (($key = array_search($search, $array[$i])) !== false) {
            var_dump(array($i, $key));
        }
    }
    

    【讨论】:

    • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of howwhy 这解决了问题。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
    【解决方案3】:

    试试:

    $search = 'really';
    
    $index = -1;
    $location = [];
    
    foreach($i = 0; $i < sizeof($array); $i++){
        for($j = 0; $j < sizeof($array[$i]); $j++){
            if($search == $array[$i][$j]){
                $location = [$i, $j];
                $index++;
                break;
            } else {
                $index++;
            }
        } 
    }
    
    print_r($location); // This gives you the position where the match is found i.e. [2, 0];
    echo $index; // This is the direct index of the search result i.e. 6
    
    print($index);
    

    这应该可行。没机会尝试,但应该...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      相关资源
      最近更新 更多