Sangit
Sangit

Reputation: 159

Filter elements from multidimensional array that contain specific string

I have the following array

Array
(
[0] => Array
    (
        [text] => Array
            (
                [content] => I
                [beginOffset] => 0
            )

        [partOfSpeech] => Array
            (
                [tag] => PRON
                [aspect] => ASPECT_UNKNOWN
                [case] => NOMINATIVE
                [form] => FORM_UNKNOWN
                [gender] => GENDER_UNKNOWN
                [mood] => MOOD_UNKNOWN
                [number] => SINGULAR
                [person] => FIRST
                [proper] => PROPER_UNKNOWN
                [reciprocity] => RECIPROCITY_UNKNOWN
                [tense] => TENSE_UNKNOWN
                [voice] => VOICE_UNKNOWN
            )

        [dependencyEdge] => Array
            (
                [headTokenIndex] => 1
                [label] => NSUBJ
            )

        [lemma] => I
    )
...

I want to remove all elements that contain the string "_UNKNOWN" as they are not necessairy

how would I go about that?

Upvotes: 0

Views: 31

Answers (1)

Milan Chheda
Milan Chheda

Reputation: 8249

Assuming all your 'UNKNOWN' are going to be in 'partOfSpeech', you can use this simple code to remove all the elements containing the string '_UNKNOWN':

$array = ['text' => ['content' => 'I', 'beginOffset' => 0], 'partOfSpeech' => ['tag' => 'PRON', 'aspect' => 'ASPECT_UNKNOWN', 'form' => 'FORM_UNKNOWN']]; // Example array

$array['partOfSpeech'] = array_filter($array['partOfSpeech'], 
  function($item) { 
    return strpos($item, '_UNKNOWN') === false; 
  });

print_r($array);

Output:

Array ( [text] => Array ( [content] => I [beginOffset] => 0 ) [partOfSpeech] => Array ( [tag] => PRON ) )

Upvotes: 1

Related Questions