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

Try like this may help you:

$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 に答える