2013-07-22 3 views
2

다차원 배열의 모든 키 (/부터)를 카멜 케이스로 변환하는 함수를 만들려고합니다.PHP 키를 다차원 배열로 변환

function transformKeys(&$array, $direction = 'to') 
{ 
    if (is_array($array)) { 
     foreach (array_keys($array) as $key) { 
      $value = &$array[$key]; 
      unset($array[$key]); 
      if ($direction == 'to') 
       $transformedKey = toCamelCase($key); 
      else 
       $transformedKey = fromCamelCase($key); 


      if (is_array($value)) 
       transformKeys($value, $direction); 

      if (isset($array[$transformedKey]) && is_array($array[$transformedKey])) { 
       $array[$transformedKey] = array_merge($array[$transformedKey], $value); 
      } 
      else 
       $array[$transformedKey] = $value; 
      unset($value); 
     } 

    } 
    return $array; 
    } 

function toCamelCase($string, $sepp = '_') 
{ 
    $str = str_replace(' ', '', ucwords(str_replace($sepp, ' ', $string))); 
    $str[0] = strtolower($str[0]); 
    return $str; 
} 

function fromCamelCase($string, $sepp = '_') 
{ 
    preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $string, $matches); 
    $ret = $matches[0]; 
    foreach ($ret as &$match) { 
     $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); 
    } 
    return implode($sepp, $ret); 
} 

배열 : I 이너 어레이 배열의 마지막 요소로서 나오는 I 이유 알아낼 수 배열의 어레이를 가질 때 문제가 여기

함수이다 .. 인 ..

{ 
    "id": 23, 
    "name": "FOO SA", 
    "taxIdentifier_id": "309", 
    "activityType": "UTILITY", 
    "currencyCode": "USD", 
    "contacts": [ 
     { 
      "id": 7, 
      "firstName": "Bla", 
      "lastName": "Bla", 
      "gender": "M", 
      "supplierId": 23 
     }, 
     { 
      "id": 8, 
      "firstName": "Another", 
      "lastName": "Value", 
      "gender": "M", 
      "supplierId": 23 
     } 
    ] 
} 

그 결과 ...

Array 
(
    [id] => 23 
    [name] => FOO SA 
    [tax_identifier_id] => 309 
    [activity_type] => UTILITY 
    [currency_code] => USD 
    [contacts] => Array 
     (
      [] => Array 
       (
        [id] => 8 
        [first_name] => Another 
        [last_name] => Value 
        [gender] => M 
        [supplier_id] => 23 
       ) 

     ) 

) 

어떤 아이디어를이 같은 것입니다?

감사합니다.

+0

는 JSON 형식으로 소스입니까? – verbumSapienti

+0

예 소스는 json 문자열에서 온 것입니다. – FMQ

답변

2

귀하의 fromCamelCase() 기능은 숫자 배열 키에 대한 잘못된 값을 제공 : 나는 또한 일부 단순화를했습니다

function fromCamelCase($key) 
{ 
    return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $key)); 
} 

: 여기

var_dump(fromCamelCase(1)); // string(0) "" 

같은 단점으로 고생하지 않는 구현입니다 당신의 디자인; 대신 고정 기능을 사용하는 나는 그것이 일반적인했습니다 :

function array_changekey_recursive(array &$array, $callback) 
{ 
    foreach ($array as $key => &$value) { 
     if (is_array($value)) { 
      array_changekey_recursive($value, $callback); 
     } 

     $new_key = call_user_func($callback, $key); 
     // only update where necessary 
     if (strcmp($new_key, $key) != 0) { 
      unset($array[$key]); 
      $array[$new_key] = $value; 
     } 
    } 
} 

를 호출하려면 :

array_changekey_recursive($arr, 'fromCamelCase'); 
+0

대단히 고마워요, 이것은 매력처럼 작동했습니다! 문제는 "fromCamelCase"함수에서 발생했지만 changeKey 구현이 더 간단합니다. 다시 한 번 감사드립니다! – FMQ

관련 문제