1

I have an array full of lines from a text file. I'm using preg_match to find the lines in this array that contain a certain string.

Each time I find a match I want to push the key value for that line to another array so I end up with an array full of keys where the matches occur. I then want to iterate through this new array and perform an action for each match.

How can I push just the keys to a new array?

4

3 回答 3

2

像这样尝试可能会对您有所帮助:

$secondArray    = array();
foreach( $firstArray as $key=>$each ){
    if( your_condition_here ){
        $secondArray[]  = $key;    
    }

}
print_r( $secondArray );die;
于 2013-09-23T08:36:01.573 回答
1

array_keys() 函数是您正在寻找的。

http://php.net/manual/en/function.array-keys.php

这回答了“我怎样才能将键推送到新数组?”

但我认为 Nil'z 将 preg_match() 置于循环中的方向是正确的。

您可能还想查看函数 array_walk() 来处理数组中的每个元素

http://php.net/manual/en/function.array-walk.php

那么这段代码呢

$matching_keys = array();
array_walk($filelines, function($line, $key) {
    if(preg_match(...))
        $matching_keys[] = $key
});
array_walk($matching_keys, function($matching_key) {
    //do your code
});
于 2013-09-23T08:37:57.760 回答
0

尝试这个 :

$new_arr = array_keys($array);
于 2013-09-23T08:38:45.663 回答