PHP搜索子字符串的多维数组

时间:2012-09-19 19:49:20

标签: php arrays substring

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

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

1 个答案:

答案 0 :(得分: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 *函数系列,更多详细信息here)。