簡體   English   中英

如果它包含搜索數組中的某些字符串,如何取消設置數組鍵?

[英]How to unset array key if it contains certain string from search array?

我的數組打印看起來像這樣print_r($ myArray);

Array
(
     [http://link_to_the_file/stylename2.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )

    [http://link_to_the_file/stylename1.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )

    [http://link_to_the_file/stylename5.css] => Array
        (
            [mime] => text/css
            [media] => 
            [attribs] => Array
                (
                )

        )
)

我需要找到樣式名稱2和5並取消設置它們,但我想僅通過它們的名稱而不是完整的數組鍵來查找它們。 所以我把搜索詞放在數組中。

$findInArray = array('stylename2.css','stylename5.css');


foreach($myArray as $path => $file ){


    //  if $path contains a string from $findInArray 
       unset $myArray [$path];

}

最好的方法是什么? 我嘗試了array_key_exists,但它只匹配確切的鍵值。 謝謝!

嘗試這個:

$findInArray = array('stylename2.css','stylename5.css');
foreach($myArray as $path => $file ){
      foreach($findInArray as $find){
           if(strpos($path, $find) !== false)
              unset($myArray[$path]);
      }
}

您可以為此使用PHP in_array()函數。

foreach($myArray as $path => $file) {
    if(in_array(basename($path), $findInArray)) {
        unset($myArray[$path]);
    }
}

使用basename()in_array()

foreach($myArray as $path => $file ){
    $filename = basename($path);
    if (in_array($filename, $findInArray)) {
        unset($myArray[$path]);
    }
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM