array_combine

array_combine


函数说明参数什么的去官网查就行了,不再赘述,此文只列举一些工作中使用到的。

  1. 基础

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    $a = array(
    'onekey1' => 'onevalue1',
    'onekey2' => 'onevalue2',
    'onekey3' => 'onevalue3'
    );

    $b = array(
    'twokey1' => 'twovalue1',
    'twokey2' => 'twovalue2',
    'twokey3' => 'twovalue3'
    );

    $c = array_combine($a, $b);

    print_r($c);

    ##结果

    Array
    (
    'onevalue1' => 'twovalue1',
    'onevalue2' => 'twovalue2',
    'onevalue3' => 'twovalue3'
    )
  2. 场景

  • 原数组
1
2
3
4
5
6
$season   = [
['id' => 'aaa', 'name' => '春季', 'sequence' => 1],
['id' => 'bbb', 'name' => '暑假', 'sequence' => 2],
['id' => 'ccc', 'name' => '秋季', 'sequence' => 3],
['id' => 'ddd', 'name' => '寒假', 'sequence' => 4],
];

打印一下原数组:print_r($season);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Array
(
[0] => Array
(
[id] => 1
[name] => 春季
[sequence] => 1
)

[1] => Array
(
[id] => 2
[name] => 暑假
[sequence] => 2
)

[2] => Array
(
[id] => 3
[name] => 秋季
[sequence] => 3
)

[3] => Array
(
[id] => 4
[name] => 寒假
[sequence] => 4
)

)

  • 取$season的id组成新数组$season_id
1
$season_id  = array_column($season, 'id');

打印一下:print_r($season_id);

1
2
3
4
5
6
7
Array
(
[0] => aaa
[1] => bbb
[2] => ccc
[3] => ddd
)

1
$new_season = array_combine($season_id, $season);

打印一下需要的结果:print_r($new_season);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Array
(
[aaa] => Array
(
[id] => aaa
[name] => 春季
[sequence] => 1
)

[bbb] => Array
(
[id] => bbb
[name] => 暑假
[sequence] => 2
)

[ccc] => Array
(
[id] => ccc
[name] => 秋季
[sequence] => 3
)

[ddd] => Array
(
[id] => ddd
[name] => 寒假
[sequence] => 4
)

)