通过数组中存在的子数组递归查找和替换数组值

问题描述

我有一个 JSON,如下例所示:

{
  "a": {
    "type": "record","name": "test","fields": [
      {
        "name": "b","type": "b"
      }
    ]
  },"d": {
    "type": "record","name": "d"
  },"c": {
    "type": "record","name": "b","fields": [
      {
        "name": "d","type": "d"
      }
    ]
  },"b": {
    "type": "record","name": "Core","fields": [
      {
        "name": "test","type": "c"
      },{
        "name": "testMulti","type": [
          "null","c"
        ]
      }
    ]
  }
}

递归地,在这个数组中,有一个名为key的{​​{1}}。例如,type。我正在寻找一种方法来查找 "type" => "b" 并将 $key == 'type'value 替换为具有相同名称keyvalue

例如,在子数组key中,其中a代码应该替换键"type" => "b"的值,即子数组b和以此类推。

搜索和替换后应该是这样的。

b

如您所见,所有类型都被键的值替换了。 例如,{ "a": { "type": "record","type": { "type": "record","fields": [ { "name": "test","type": { "type": "record","fields": [ { "name": "d","type": { "type": "record","name": "d" } } ] } },{ "name": "testMulti","type": [ "null",{ "type": "record","fields": [ { "name": "d","type": { "type": "record","name": "d" } } ] } ] } ] } } ] } } 被替换为值 "type" => "b" 等等。

我创建了一个使用递归遍历所有键的函数,但我坚持将子数组合并回一个完整的数组。

"b"
private function mergeSchema($schemaArray) {
        foreach ($schemaArray as $key => $value) {
            // p_r($key,$value);
            if(is_array($value)) {
                // echo 'in array' . PHP_EOL;
                $schemaArray = $this->mergeSchema($value);
            }
            if($key == 'type' && !(is_named_type($value) || is_primitive_type($value))) {
                p_R($value);
            }
        }
        return $schemaArray;
    }

任何帮助将不胜感激。非常感谢您的关注和参与。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)