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

时间:2013-07-28 06:53:07

标签: php multidimensional-array replace preg-match str-replace

我正在寻找执行以下操作的最佳方式:

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

我基本上想在所有值中查找关键字文本,无论哪个文本删除它们,而是创建一个新值“有文本问题”

和格式一样,它将删除最后两个值并创建一个说“使用了错误的格式”

所以我的最终数组看起来像是

 [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 ??
 }

2 个答案:

答案 0 :(得分:1)

尝试递归函数,该函数遍历整个数组和子数组,并在非数组值中搜索$ 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()。

答案 1 :(得分:0)

我认为这应该有效:

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'])

但是,如果最后一个数组是非关联的,那么甚至可以采用更简单的方法解决问题。