簡體   English   中英

在關聯數組php的鍵和值內搜索字符串

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

我有一個數組看起來像這樣一擊 =>

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

我如何在其中搜索“[+]”或“[-]”之類的詞並用其他內容替換它們?
ps:想在關聯數組的鍵和值中搜索和替換
另一個 ps:我在谷歌或這個論壇中找不到任何我希望的東西

使用您的示例數據,您可以嵌套任意深度,直到 PHP 的遞歸限制。

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

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

這是一個簡單的遞歸函數來替換鍵和值

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;
}

將打印出來

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

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM