简体   繁体   中英

PHP search multidimensional array for substring

I'm trying to search for a substring within part of the bottom layer of a 2-layer array and return the key from the top layer. Eg in the array below searching within "A" for "ca" would return "0" and "2" (but would miss "cattle"):

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

You can try like this :

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

Will output :

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

Note that this method is not encoding safe (you may use mb_str* instead of str* function family, more details here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM