English 中文(简体)
• 如何将次线钥匙改名为PHP? [复制]
原标题:How to rename sub-array keys in PHP? [duplicate]
  • 时间:2012-03-07 16:15:47
  •  标签:
  • php

当我用一个称为“标签”(多层面阵列)的可变数来计算时,我会这样做:

Array
(
    [0] => Array
        (
            [name] => tabbing
            [url] => tabbing
        )

    [1] => Array
        (
            [name] => tabby ridiman
            [url] => tabby-ridiman
        )

    [2] => Array
        (
            [name] => tables
            [url] => tables
        )

    [3] => Array
        (
            [name] => tabloids
            [url] => tabloids
        )

    [4] => Array
        (
            [name] => taco bell
            [url] => taco-bell
        )

    [5] => Array
        (
            [name] => tacos
            [url] => tacos
        )
)

我愿重新命名所有阵列钥匙,称作“价值”。 这样做有什么好办法?

最佳回答

You could use array_map() to do it.

$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 ]);
}

收留中心改称关键功能:

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

谈论功能性 PHP,我有这一更一般性的答复:

    array_map(function($arr){
        $ret = $arr;
        $ret[ value ] = $ret[ url ];
        unset($ret[ url ]);
        return $ret;
    }, $tag);
}
foreach ($basearr as &$row)
{
    $row[ value ] = $row[ url ];
    unset( $row[ url ] );
}

unset($row);

这应在大多数版本的PHP 4+中进行。 使用匿名功能的射线图不支持5.3。

另外,在使用严格的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"));

它使用类似于预支款,即旧金_和新元key的数额应当相同。 然而,如果它们不是空白钥匙,则增加。 这意味着,如果在你的阵列中出现图象,你就可以利用这一办法。

利用这一时间,希望它有助于!

采用非常简单的办法来取代多层面阵列中的钥匙,甚至可能是一种危险的轨道,但如果你对源阵列有某种控制,则应当加以罚款:

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

这至少是困难的。 无论阵列在多维阵列中的深度如何,你可以简单地分配周围的阵列:

$array[ key_new ] = $array[ key_old ];
unset($array[ key_old ]);
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);
    }
}

Use:

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/Replace-keys-in-array

这就是我如何重新命名钥匙,特别是用电子表格上载的数据:

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

Based on the great solution provided by Alex, I created a little more flexible solution based on a scenario I was dealing with. So now you can use the same function for multiple arrays with different numbers of nested key pairs, you just need to pass in an array of key names to use as replacements.

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

www.un.org/Depts/DGACM/index_spanish.htm 页: 1

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




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签