PHP 更改数组键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/308703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 22:20:16  来源:igfitidea点击:

PHP Change Array Keys

php

提问by Eric Goodwin

Array( 0 => 'blabla',
       1 => 'blabla',
       2 => 'blblll' ) etc..

Is there a way to change all the numeric keys to "Name" without looping through the array (so a php function)?

有没有办法在不循环遍历数组的情况下将所有数字键更改为“名称”(所以是 php 函数)?

回答by Eric Goodwin

If you have an array of keys that you want to use then use array_combine

如果您有要使用的键数组,请使用 array_combine

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

给定 $keys = array('a', 'b', 'c', ...) 和你的数组 $list,然后执行以下操作:

$list = array_combine($keys, array_values($list));

List will now be array('a' => 'blabla 1', ...) etc.

列表现在将是 array('a' => 'blabla 1', ...) 等。

You have to use array_valuesto extract just the values from the array and not the old, numeric, keys.

您必须使用array_values仅从数组中提取值,而不是旧的数字键。

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

这看起来很好很简单,但是 array_values 制作了数组的完整副本,因此您可能会遇到空间问题。我们在这里所做的只是让 php 为我们做循环,而不是消除循环。我很想做一些更像的事情:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;
}

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

我不认为它比第一个代码更有效,但它提供了更多的控制并且不会有数组长度的问题。

回答by Kent Fredric

No, there is not, for starters, it is impossible to have an array with elements sharing the same key

不,对于初学者来说,不可能有一个元素共享相同键的数组

$x =array(); 
$x['foo'] = 'bar' ; 
$x['foo'] = 'baz' ; #replaces 'bar'

Secondarily, if you wish to merely prefix the numbers so that

其次,如果您只想在数字前面加上前缀,以便

$x[0] --> $x['foo_0']  

That is computationally implausible to do without looping. No php functions presently exist for the task of "key-prefixing", and the closest thing is "extract"which will prefix numeric keys prior to making them variables.

如果没有循环,这在计算上是不可能的。目前不存在用于“键前缀”任务的 php 函数,最接近的是“提取”,它将在使数字键成为变量之前为其添加前缀。

The very simplest way is this:

最简单的方法是这样的:

function rekey( $input , $prefix ) { 
    $out = array(); 
    foreach( $input as $i => $v ) { 
        if ( is_numeric( $i ) ) { 
            $out[$prefix . $i] = $v; 
            continue; 
        }
        $out[$i] = $v;
    }
    return $out;
}

Additionally, upon reading XMLWriter usage, I believe you would be writing XML in a bad way.

此外,在阅读 XMLWriter 用法时,我相信您会以一种糟糕的方式编写 XML。

<section> 
    <foo_0></foo_0>
   <foo_1></foo_1>
   <bar></bar>
   <foo_2></foo_2>
</section>

Is not good XML.

不是很好的 XML。

<section> 
   <foo></foo>
   <foo></foo>
   <bar></bar>
   <foo></foo>
</section>

Is better XML, because when intrepreted, the names being duplicate don't matter because they're all offset numerically like so:

是更好的 XML,因为在解释时,重复的名称无关紧要,因为它们都在数字上偏移,如下所示:

section => { 
    0 => [ foo , {} ]
    1 => [ foo , {} ]
    2 => [ bar , {} ]
    3 => [ foo , {} ] 
}

回答by Ligemer

I added this for an answer to another question and seemed relevant. Hopefully might help someone that needs to change the value of the keys in an array. Uses built-in functions for php.

我添加了这个来回答另一个问题,看起来很相关。希望可以帮助需要更改数组中键值的人。使用 php 的内置函数。

$inputArray = array('app_test' => 'test', 'app_two' => 'two');

/**
 * Used to remap keys of an array by removing the prefix passed in
 * 
 * Example:
 * $inputArray = array('app_test' => 'test', 'app_two' => 'two');
 * $keys = array_keys($inputArray);
 * array_walk($keys, 'removePrefix', 'app_');
 * $remappedArray = array_combine($keys, $inputArray);
 *
 * @param $value - key value to replace, should be from array_keys
 * @param $omit - unused, needed for prefix call
 * @param $prefix - prefix to string replace in keys
 */
function removePrefix(&$value, $omit, $prefix) {
    $value = str_replace($prefix, '', $value);
}

// first get all the keys to remap
$keys = array_keys($inputArray);

// perform internal iteration with prefix passed into walk function for dynamic replace of key
array_walk($keys, 'removePrefix', 'app_');

// combine the rewritten keys and overwrite the originals
$remappedArray = array_combine($keys, $inputArray);

// see full output of comparison
var_dump($inputArray);
var_dump($remappedArray);

Output:

输出:

array(2) {
  'attr_test' =>
  string(4) "test"
  'attr_two' =>
  string(3) "two"
}
array(2) {
  'test' =>
  string(4) "test"
  'two' =>
  string(3) "two"
}

回答by Aurelien

$prefix = '_';
$arr = array_combine(
    array_map(function($v) use ($prefix){
       return $prefix.$v;
    }, array_keys($arr)),
    array_values($arr)
);

回答by dingyuchi

change array key name "group" to "children".

将数组键名“group”更改为“children”。

<?php
echo json_encode($data);

function array_change_key_name( $orig, $new, &$array ) {
    foreach ( $array as $k => $v ) {
        $res[ $k === $orig ? $new : $k ] = ( (is_array($v)||is_object($v)) ? array_change_key_name( $orig, $new, $v ) : $v );
    }
    return $res;
}

echo '<br>=====change "group" to "children"=====<br>';
$new = array_change_key_name("group" ,"children" , $data);
echo json_encode($new);
?>

result:

结果:

{"benchmark":[{"idText":"USGCB-Windows-7","title":"USGCB: Guidance for Securing Microsoft Windows 7 Systems for IT Professional","profile":[{"idText":"united_states_government_configuration_baseline_version_1.2.0.0","title":"United States Government Configuration Baseline 1.2.0.0","group":[{"idText":"security_components_overview","title":"Windows 7 Security Components Overview","group":[{"idText":"new_features","title":"New Features in Windows 7"}]},{"idText":"usgcb_security_settings","title":"USGCB Security Settings","group":[{"idText":"account_policies_group","title":"Account Policies group"}]}]}]}]}

=====change "group" to "children"=====

{"benchmark":[{"idText":"USGCB-Windows-7","title":"USGCB: Guidance for Securing Microsoft Windows 7 Systems for IT Professional","profile":[{"idText":"united_states_government_configuration_baseline_version_1.2.0.0","title":"United States Government Configuration Baseline 1.2.0.0","children":[{"idText":"security_components_overview","title":"Windows 7 Security Components Overview","children":[{"idText":"new_features","title":"New Features in Windows 7"}]},{"idText":"usgcb_security_settings","title":"USGCB Security Settings","children":[{"idText":"account_policies_group","title":"Account Policies group"}]}]}]}]}

回答by dingyuchi

The solution to when you're using XMLWriter(native to PHP 5.2.x<) is using $xml->startElement('itemName');this will replace the arrays key.

当您使用XMLWriter(原生于PHP 5.2.x<)时的解决方案是使用$xml->startElement('itemName');this 将替换数组键。

回答by intel

I think that he want:

我认为他想要:

$a = array(1=>'first_name', 2=>'last_name');
$a = array_flip($a);

$a['first_name'] = 3;
$a = array_flip($a);

print_r($a);

回答by Darren Cato

I did this for an array of objects. Its basically creating new keys in the same array and unsetting the old keys.

我为一组对象做了这个。它基本上在同一个数组中创建新键并取消设置旧键。

public function transform($key, $results)
{
    foreach($results as $k=>$result)
    {
        if( property_exists($result, $key) )
        { 
            $results[$result->$key] = $result;
            unset($results[$k]);
        }
    }

    return $results;
}

回答by Darren Cato

Use array array_flipin php

array_flip在 php 中使用数组

$array = array ( [1] => Sell [2] => Buy [3] => Rent [4] => Jobs )
print_r(array_flip($array));
Array ( [Sell] => 1 [Buy] => 2 [Rent] => 3 [Jobs] => 4 ) 

回答by Red Web

<?php
    $array[$new_key] = $array[$old_key];
    unset($array[$old_key]);
?>