Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

replace key in php

### Deeply recursive change keys with array and object data
public function recursiveChangeKey($arr, $set)
    {
        //$arr => original array
        //$set => array containing old keys as keys and new keys as values

        if (!is_array($arr) && !is_object($arr) || !is_array($set)) {
            return $arr;
        }
        $newArr = [];
        if (is_array($arr) && is_array($set)) {
            foreach ($arr as $k => $v) {
                $key = array_key_exists($k, $set) ? $set[$k] : $k;
                $newArr[$key] = is_array($v) ? self::recursiveChangeKey($v, $set) : $v;
            }
        } elseif (is_object($arr) || is_object($set)) {
            $set = (array) $set;
            foreach ($arr->toArray() as $k => $v) {
                $key = array_key_exists($k, $set) ? $set[$k] : $k;
                $newArr[$key] = is_array($v) ? self::recursiveChangeKey($v, $set) : $v;
            }
        }
        return $newArr;
    }
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #replace #key #php
ADD COMMENT
Topic
Name
9+4 =