Home >Backend Development >PHP Problem >How to change array key name in php

How to change array key name in php

王林
王林Original
2020-07-23 15:44:343524browse

The way php changes the array key name is: you can change it through the array_combine() function. This function creates a new array by merging two arrays, one with keys and the other with keys. The number of elements in the key array and the key value array must be the same.

How to change array key name in php

Function introduction:

(Recommended tutorial: php tutorial)

array_combine The () function creates a new array by merging two arrays, where the elements of one array are key names and the elements of the other array are key values. The number of elements in the key name array and the key value array must be the same!

array_slice() function returns the selected portion of the array. If the array has string keys, the returned array will retain the keys.

Code implementation:

$ar = array(
 array(1 => 'a', 2 => 50, 3 => 60, 4 => 'long', 5 => 'zzz', 6 => 'kkk', 7 => 'ooo'),
 array(1 => 'b', 2 => 60, 3 => 70, 4 => 'king', 5 => 'lll', 6 => 'ttt', 7 => 'ppp'),
 array(1 => 'c', 2 => 70, 3 => 80, 4 => 'quit', 5 => 'qqq', 6 => 'xxx', 7 => 'ccc'),
);
$kname = array('StaffId', 'Wage', 'Name', 'Work', 'Type');
function foo(&$v, $k, $kname) {
 $v = array_combine($kname, array_slice($v, 1, -1));
}
array_walk($ar, 'foo', $kname);
print_r($ar);

Input result:

Array
(
  [0] => Array
    (
      [StaffId] => 50
      [Wage] => 60
      [Name] => long
      [Work] => zzz
      [Type] => kkk
    )
  [1] => Array
    (
      [StaffId] => 60
      [Wage] => 70
      [Name] => king
      [Work] => lll
      [Type] => ttt
    )
  [2] => Array
    (
      [StaffId] => 70
      [Wage] => 80
      [Name] => quit
      [Work] => qqq
      [Type] => xxx
    )
)

The above is the detailed content of How to change array key name in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn