PHP :给定子键名称时,将关联数组的键重命名为子元素的值

PHP : Rename keys of associative array to the value of a child element when given the childs key name

是否有一个我错过的 PHP 函数,它会在给定子数组(关联数组)的键名时更改父数组的键,或者至少有一个 foreach 循环的替代方法我现在正在使用它来更改密钥。

示例数组

    $arr = array( 
        array(
            'id' => 1,
            'name' => 'one',
        ),
        array(
            'id' => 2,
            'name' => 'two',
        ),
        array(
            'id' => 3,
            'name' => 'three',
        ) 
    ); 

我希望它能像这样工作..

$arr_name = array_change_key($arr,'name');
print_r($arr_name);
$arr_name => array( 
        'one', => array(
            'id' => 1,
            'name' => 'one',
        ),
        'two' => array(
            'id' => 2,
            'name' => 'two',
        ),
        'three' => array(
            'id' => 3,
            'name' => 'three',
        ) 
    );
//$arr is unchanged

这只是额外增加的(不确定是否可能)

array_change_key($arr,'name');
print_r($arr);

//$arr has changed because it doesn't have a variable to set 
$arr => array( 
        'one', => array(
            'id' => 1,
            'name' => 'one',
        ),
        'two' => array(
            'id' => 2,
            'name' => 'two',
        ),
        'three' => array(
            'id' => 3,
            'name' => 'three',
        ) 
    );

print_r($arr[0]); //undefined index

如果我对问题的理解正确,则类似于:

$arr = array_combine(
    array_column($arr, 'name'),
    $arr
);

将使用每条记录中的 name 值作为父键,并给出

array(3) {
  ["one"]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(3) "one"
  }
  ["two"]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(3) "two"
  }
  ["three"]=>
  array(2) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(5) "three"
  }
}

你必须告诉函数是否要 "pass by reference" 它无法知道你是否试图将返回的结果设置为一个变量;

function array_change_key(array &$array, $key, $pass_by_reference = false){

    if($pass_by_reference){

       // check is_scalar($key)
       if(!is_scalar($key)) return FALSE; 
       // we already know isset($array), is_array($array) and isset(key) are true because $pass_by_reference is true;

        $array = markBakersAnswer($array,$key);

        return TRUE;
        //  pass-by-reference functions usually return true or false
    }
    return markBakersAnswer($array,$key);
}

+1

$new_array = array_change_key($arr, 'name');        // $arr unchanged and $new_array == array with new keys
$new_array = array_change_key($arr, 'name', false); // $arr unchanged and $new_array == array with new keys

$new_array = array_change_key($arr, 'name', true);  // $arr changed (new keys),  $new_array = TRUE;
$new_array = array_change_key($arr, array(), true); // $arr changed (new keys),  $new_array = FALSE;