1

我正在尝试在 2 层数组的底层部分中搜索子字符串,并从顶层返回密钥。例如,在下面的数组中在“A”中搜索“ca”将返回“0”和“2”(但会错过“cattle”):

Array (
    [0] => Array (
        [A] => cat
        [B] => horses
        )
    [1] => Array (
        [A] => dog
        [B] => cattle
    )
    [2] => Array (
        [A] => cat
        [B] => sheep
    )
) 
4

1 回答 1

1

你可以这样尝试:

$array = array(
    array(
        "A" => "cat",
        "B" => "horse"
    ),
    array(
        "A" => "dog",
        "B" => "cattle"
    ),
    array(
        "A" => "cat",
        "B" => "sheep"
    ),
);

$result = mySearch($array, "A", "ca");

function mySearch($array, $key, $search)
{
    $results = array();
    foreach ($array as $rootKey => $data) {
        if (array_key_exists($key, $data)) {
            if (strncmp($search, substr($data[$key], 0, 2), strlen($search)) == 0) {
                $results[] = $rootKey;
            }
        }
    }
    return $results;
}

var_dump($result);

将输出:

array(2) {
  [0]=>
  int(0)
  [1]=>
  int(2)
}

请注意,此方法不是编码安全的(您可以使用 mb_str* 代替 str* 函数族,更多详细信息请参见此处)。

于 2012-09-19T20:04:29.987 回答