简体   繁体   English

在关联数组php的键和值内搜索字符串

[英]search string inside key and values of a associative array php

I have a array looks like this one blow =>我有一个数组看起来像这样一击 =>

$aarray = [
  "table" => "Balance",
  "where" => ["Balance[+]" => "NOMONEY[-]"]
     ];

how i can search through that for words like "[+]" or "[-]" and replace them with something else ?我如何在其中搜索“[+]”或“[-]”之类的词并用其他内容替换它们?
ps : wanna search and replace in both key and value of associative array ps:想在关联数组的键和值中搜索和替换
another ps : I cant find anything doing same as i wish in google or this forum另一个 ps:我在谷歌或这个论坛中找不到任何我希望的东西

Using your sample data, you could nest as deep as you want until PHP's recursion limit.使用您的示例数据,您可以嵌套任意深度,直到 PHP 的递归限制。

$array = [
    "table" => "Balance",
    "where" => ["Balance[+]" => "NOMONEY[-]"],
];

$new = replaceInArray($array, "[-]", "(minus)");
$new = replaceInArray($new, "[+]", "(plus)");
print_r($new);

Here is a simple recursive function to replace keys and values这是一个简单的递归函数来替换键和值

function replaceInArray($array, $search, $replace, &$newArray = [])
{
    foreach ($array as $key => $value) {
        $key = str_replace($search, $replace, $key);
        if (is_array($value)) {
            $newArray[$key] = replaceInArray($value, $search, $replace);
        } else {
            $newArray[$key] = str_replace($search, $replace, $value);
        }
    }

    return $newArray;
}

will print out将打印出来

Array
(
    [table] => Balance
    [where] => Array
        (
            [Balance(plus)] => NOMONEY(minus)
        )

)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM