source

PHP에서 하위 배열 키의 이름을 바꾸려면 어떻게 해야 합니까?

goodcode 2022. 11. 5. 11:44
반응형

PHP에서 하위 배열 키의 이름을 바꾸려면 어떻게 해야 합니까?

$tags(다차원 배열)라는 변수에서 var_dump를 실행하면 다음과 같이 표시됩니다.

어레이([0] => 어레이([name] => 탭[url] => 탭)
[1] => 어레이([name] => tabby ridiman[url] => 태비리디만)
[2] => 어레이([name] => 테이블[url] => 테이블)
[3] => 어레이([이름] => 타블로이드[url] => 타블로이드)
[4] => 어레이([이름] => 타코벨[url] => 타코벨)
[5] => 어레이([name] => 타코[url] => 타코))

"url"이라는 모든 어레이 키의 이름을 "value"로 바꾸고 싶습니다.어떻게 하면 좋을까요?

네가 할 수 있을 거야.

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

루프 스루, 새 키 설정, 이전 키 설정 해제

foreach($tags as &$val){
    $val['value'] = $val['url'];
    unset($val['url']);
}

기능적인 PHP에 대해서 말하자면, 보다 일반적인 답변을 드리겠습니다.

    array_map(function($arr){
        $ret = $arr;
        $ret['value'] = $ret['url'];
        unset($ret['url']);
        return $ret;
    }, $tag);
}

반복적인 php 이름 변경 키 함수:

function replaceKeys($oldKey, $newKey, array $input){
    $return = array(); 
    foreach ($input as $key => $value) {
        if ($key===$oldKey)
            $key = $newKey;

        if (is_array($value))
            $value = replaceKeys( $oldKey, $newKey, $value);

        $return[$key] = $value;
    }
    return $return; 
}
foreach ($basearr as &$row)
{
    $row['value'] = $row['url'];
    unset( $row['url'] );
}

unset($row);

이 기능은 대부분의 PHP 4+ 버전에서 작동합니다. 5.3 이하에서는 익명 함수를 사용하는 배열 맵이 지원되지 않습니다.

또한 foreach 예제에서는 엄격한 PHP 오류 처리를 사용할 때 경고가 발생합니다.

여기 작은 다차원 키 이름 바꾸기 기능이 있습니다.또한 어레이를 처리하여 애플리케이션 전체에서 올바른 키를 사용할 수도 있습니다.키가 존재하지 않는 경우 오류가 발생하지 않습니다.

function multi_rename_key(&$array, $old_keys, $new_keys)
{
    if(!is_array($array)){
        ($array=="") ? $array=array() : false;
        return $array;
    }
    foreach($array as &$arr){
        if (is_array($old_keys))
        {
            foreach($new_keys as $k => $new_key)
            {
                (isset($old_keys[$k])) ? true : $old_keys[$k]=NULL;
                $arr[$new_key] = (isset($arr[$old_keys[$k]]) ? $arr[$old_keys[$k]] : null);
                unset($arr[$old_keys[$k]]);
            }
        }else{
            $arr[$new_keys] = (isset($arr[$old_keys]) ? $arr[$old_keys] : null);
            unset($arr[$old_keys]);
        }
    }
    return $array;
}

사용법은 간단합니다.예시와 같이 단일 키를 변경할 수 있습니다.

multi_rename_key($tags, "url", "value");

또는 보다 복잡한 멀티키

multi_rename_key($tags, array("url","name"), array("value","title"));

preg_replace()와 유사한 구문을 사용합니다.여기서 $old_keys와 $new_keys의 양은 같아야 합니다.그러나 공백 키가 아닌 경우 키가 추가됩니다.즉, 이를 사용하여 if 스키마를 배열에 추가할 수 있습니다.

항상 이걸 사용하세요. 도움이 되길 바래요!

다차원 배열의 키를 교환하는 매우 간단한 접근법입니다.또, 약간 위험할 수도 있습니다만, 소스 어레이를 어느 정도 제어할 수 있습니다.

$array = [ 'oldkey' => [ 'oldkey' => 'wow'] ];
$new_array = json_decode(str_replace('"oldkey":', '"newkey":', json_encode($array)));
print_r($new_array); // [ 'newkey' => [ 'newkey' => 'wow'] ]

이것은 조금도 어려울 필요가 없다.다차원 어레이의 깊이에 관계없이 어레이를 할당하기만 하면 됩니다.

$array['key_old'] = $array['key_new'];
unset($array['key_old']);

루프 없이 할 수 있습니다.

아래와 같이

$tags = str_replace("url", "value", json_encode($tags));  
$tags = json_decode($tags, true);
                    
class DataHelper{

    private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
        foreach ($map as $old => $new) {
            $old = preg_replace('/([\.]{1}+)$/', '', trim($old));
            if ($new) {
                if (!is_array($new)) {
                    $array[$new] = $array[$old];
                    $storage[$level][$old] = $new;
                    unset($array[$old]);
                } else {
                    if (isset($array[$old])) {
                        static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
                    } else if (isset($array[$storage[$level][$old]])) {
                        static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
                    }
                }
            }
        }
    }

    /**
     * Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
     * @param type $map
     * @param type $array
    */
    public static function renameArrayKeys($map = [], &$array = [])
    {
        $storage = [];
        static::__renameArrayKeysRecursive($map, $array, 0, $storage);
        unset($storage);
    }
}

용도:

DataHelper::renameArrayKeys([
    'a' => 'b',
    'abc.' => [
       'abcd' => 'dcba'
    ]
], $yourArray);

중복된 질문에서 나온 것입니다.

$json = '[   
{"product_id":"63","product_batch":"BAtch1","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"},    
{"product_id":"67","product_batch":"Batch2","product_quantity":"50","product_price":"200","discount":"0","net_price":"20000"}
]';

$array = json_decode($json, true);

$out = array_map(function ($product) {
  return array_merge([
    'price'    => $product['product_price'],
    'quantity' => $product['product_quantity'],
  ], array_flip(array_filter(array_flip($product), function ($value) {
    return $value != 'product_price' && $value != 'product_quantity';
  })));
}, $array);

var_dump($out);

https://repl.it/@Piterden/키 배열 치환

특히 스프레드시트에 업로드된 데이터를 사용하여 키의 이름을 변경하는 방법은 다음과 같습니다.

function changeKeys($array, $new_keys) {
    $newArray = [];

    foreach($array as $row) {
        $oldKeys = array_keys($row);
        $indexedRow = [];

        foreach($new_keys as $index => $newKey)
            $indexedRow[$newKey] = isset($oldKeys[$index]) ? $row[$oldKeys[$index]] : '';

        $newArray[] = $indexedRow;
    }

    return $newArray;
}

Alex가 제공한 뛰어난 솔루션을 바탕으로 제가 다루고 있는 시나리오를 바탕으로 좀 더 유연한 솔루션을 만들었습니다.네스트된 키쌍의 수가 다른 여러 어레이에서 동일한 기능을 사용할 수 있게 되었습니다.키 이름의 배열을 전달하기만 하면 대체됩니다.

$data_arr = [
  0 => ['46894', 'SS'],
  1 => ['46855', 'AZ'],
];

function renameKeys(&$data_arr, $columnNames) {
  // change key names to be easier to work with.
  $data_arr = array_map(function($tag) use( $columnNames) {
    $tempArray = [];
    $foreachindex = 0;
    foreach ($tag as $key => $item) {
      $tempArray[$columnNames[$foreachindex]] = $item;
      $foreachindex++;
    }
    return $tempArray;
  }, $data_arr);

}

renameKeys($data_arr, ["STRATEGY_ID","DATA_SOURCE"]);

이 일은 나에게 딱 맞는다

 $some_options = array();;
if( !empty( $some_options ) ) {
   foreach( $some_options as $theme_options_key => $theme_options_value ) {
      if (strpos( $theme_options_key,'abc') !== false) { //first we check if the value contain 
         $theme_options_new_key = str_replace( 'abc', 'xyz', $theme_options_key ); //if yes, we simply replace
         unset( $some_options[$theme_options_key] );
         $some_options[$theme_options_new_key] = $theme_options_value;
      }
   }
}
return  $some_options;

언급URL : https://stackoverflow.com/questions/9605143/how-to-rename-sub-array-keys-in-php

반응형