Home  >  Article  >  Backend Development  >  How to modify the key value of a subarray in a php array

How to modify the key value of a subarray in a php array

coldplay.xixi
coldplay.xixiOriginal
2020-10-05 13:20:283138browse

How to modify the key value of a subarray in a php array: Use the function [array_slice()] to take out a value in the array according to the conditions and return it. The syntax is [array_slice(array,offset,length,preserve)] .

How to modify the key value of a subarray in a php array

How to modify the key value of a sub-array in a php array:

Definition and usage

The array_slice() function removes a segment of value from the array based on conditions and returns it.

Note: If the array has string keys, the returned array will retain the key names.

Syntax

array_slice(array,offset,length,preserve)

Example 1

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3=>"Bird");
print_r(array_slice($a,1,2));
?>

Output:

Array
( [0] => Cat [1] => Horse )

The specific implementation is as follows:

Reference examples, complete writing:

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

If you want to know more about programming learning, please pay attention to the php training column!

The above is the detailed content of How to modify the key value of a subarray in a php array. 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