将一些数组值设置为数组的键

时间:2017-07-26 03:01:52

标签: php arrays

我已经尝试过这行代码来显示数组:

foreach($users_array as $value){    
    echo "<pre>";
    print_r($value);                     
} 

显示这种数组。

Array
(
    [auto_id] => 45
    [id] => 20151116
    [name] => Peter 2
    [department] => 
    [position] => 
    [rate] => 300
    [date_added] => 2017-07-26 09:31:44
)
Array
(
    [auto_id] => 80
    [id] => 20160410
    [name] => John 2
    [department] => 
    [position] => 
    [rate] => 400
    [date_added] => 2017-07-26 09:31:48
)

现在我想做的是让员工的id成为数组的关键,并将它们作为一个多维数组。

示例输出应该是这样的:

Array
(
    [20151116] => Array
    (
        [auto_id] => 45
        [id] => 20151116
        [name] => Peter 2
        [department] => 
        [position] => 
        [rate] => 300
        [date_added] => 2017-07-26 09:31:44
    )

    [20160410] => Array
    (
        [auto_id] => 80
        [id] => 20160410
        [name] => John 2
        [department] => 
        [position] => 
        [rate] => 400
        [date_added] => 2017-07-26 09:31:48
    )

)

感谢任何帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

最简单的方法是直接输出一个新数组,然后遍历现有数组,将id设置为新数组的索引:

<?php

$newArray = array();

foreach($users_array as $value) {
    $newArray[$value["id"]] = $value;
    print_r($newArray);
}

希望这有帮助! :)

答案 1 :(得分:0)

您需要更改

  $final = array();
  foreach($users_array as $value){    
      $final[$value["id"]] = $value;                 
  }
      echo "<pre>";
      print_r($final);  

答案 2 :(得分:0)

使用函数array_column()和array_combine(),如下所示:

$employee_id = array_column($users_array,'id');
$users_array = array_combine($employee_id,$users_array);