从包含特定字符串的多维数组中过滤元素

时间:2017-11-26 01:45:09

标签: php arrays multidimensional-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
    )
...

我想删除包含字符串“_UNKNOWN”的所有元素,因为它们不是必需的

我该怎么做?

1 个答案:

答案 0 :(得分:1)

假设您所有的'UNKNOWN'都在'partOfSpeech'中,您可以使用这个简单的代码删除包含字符串'_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);

输出:

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