douyun8885 2014-09-26 13:31
浏览 64
已采纳

如何替换多维数组中的字符串?

How can I replace a string/word that's inside a multidimensional array with a new value? I don't have its key, just know the haystack and the needle.

Say I have a multidimensional array, $submenu_arr, (don't know how many dimensions).

I want to find a value inside one of these arrays and replace it with a new value.

Actually for a translation.

Like:

 recursive_arr_translation('Article', $submenu_arr, 'Artigo');//"Artigo" is a Portuguese word for "Article".

I've tried this, but not working:

 function in_array_r($needle, $haystack, $new_value) {
        $found = false;
        foreach ($haystack as $key=>$value) {
        if ($value === $needle) { 
                $found = true; 
                $haystack[$key] = $new_value;
                return true;
            } elseif (is_array($value)) {
                $found = in_array_r($needle, $haystack[$key], $new_value); 
                if($found) { 
                    return true; 
                } 
            }    
        }
        return $found;
    }


in_array_r('Article', $submenu, 'Artigo');
in_array_r('Location', $submenu, 'Localização');

EDIT: Is working, but somehow, I don't get it working, I'm trying to translate a WordPress submenu word.

  • 写回答

1条回答 默认 最新

  • dougaopu7938 2014-09-26 14:36
    关注

    You can use array_walk_recursive as suggested in the comments, and pass your original array as reference, allowing us to edit it.

    <?php
    
    $a = array("Giraffe", "Monkey", "Elephant", "Snake", 5, "other" => array("apple", "orange"));
    
    array_walk_recursive($a, function(&$a) {
            if($a == "apple") {
                 $a = "Banana";
            }
    });
    
    echo print_r($a, true);
    

    https://eval.in/198978

    So, now we have the basic logic, let's create a function with 3 parameters.

    function replace_in_array($find, $replace, &$array) {
        array_walk_recursive($array, function(&$array) use($find, $replace) {
            if($array == $find) {
                 $array= $replace;
            }
        });
        return $array;
    }
    
    $a = array("Giraffe", "Monkey", "Elephant", "Snake", 5, "other" => array("apple", "orange"));
    echo print_r( replace_in_array("apple", "banana", $a), true);
    

    https://eval.in/198989

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?