php在查找关键字时转换数组值并合并为一


php convert array values and combine into one when finding key words

我正在寻找完成以下操作的最佳方法:

 [key] => Array
    (
        [alert] => Array
            (
                [0] => Possible text issue
                [1] => Multiple text issues
                [2] => Incorrect format
                [3] => format is not supported
            )
    )

我基本上想在所有的值中寻找关键词文本,无论哪一个值有文本,都会删除它们,并创建一个新的值"There are text issues"

格式也是一样的,它会删除最后两个值,并创建一个表示"使用了错误的格式"的

所以我的最终阵列看起来像

 [key] => Array
    (
        [alert] => Array
            (
                [0] => There are text issues
                [1] => Wrong format is used
            )
    )

关于如何做到这一点的任何想法。我会写下我迄今为止所做的一切,但我甚至不知道从哪里开始。

我正在考虑做

 foreacch ($array['key']['alert'] as $key=>$value) {
      // maybe use preg_match for specific key words or use str_replace ??
 }

尝试一个递归函数,它遍历整个数组和子数组,在非数组值中搜索$contains字符串,并用$stringToReplaceWith字符串替换整个数组元素。

function replaceArrayElementRecursiveley ($array, $contains = "text", $stringToReplaceWith = "There are text issues") {
    foreach ($array as $key=>$value){
        if (is_array($value)) {
            $array[$key] = replaceArrayElementRecursiveley($value, $contains, $stringToReplaceWith);
        } else if (stripos($value, $contains) !== false) {
            $array[$key] = $stringToReplaceWith;
        }
    }
    return $array;
}
$test = array(
    "key" => array(
        "alert" => array(
            0 => "Possible text issues",
            1 => "Multiple text issues",
            2 => "Incorrect format",
            3 => "format is not supported",
        )
    )
);
$test = replaceArrayElementRecursiveley($test);

如果你只需要搜索"text",而不需要搜索其他内容,那么在我看来,使用preg_replace是不必要的,在这种情况下,preg_match也是如此。但是,如果您需要搜索不止一个事件,则可以轻松地将stripos()切换为preg_match()。

我认为这应该有效:

foreach ($key['alert'] as $var1=>$var2)
{
     if(strstr($var2,'text'))
     {
         array_splice($var2,$var1,($var1)+1,'There are text issues');
     }
}
$Key['alert']=array_unique($Key['alert'])

但如果最后一个数组不是关联的,那么还有一种更简单的方法可以解决问题。