如何通过连接两个数组值获得一个数组

时间:2018-10-31 12:31:54

标签: php arrays multidimensional-array associative-array

我有两个数组

$column_names=array[ 0=>'student_id', 1=>'college_name', 2=>'name' ]

$student_details=array[ 0=>array [
   0=>'1', 1=>'xxx', 2=>'aaa' ], 1=>array [
   0=>'2', 1=>'yyy', 2=>'bbb' ] ] 

我想得到一个输出数组,如下所示:

 $student_details=array[ 0=>array [
'student_id'=>'1', 'college_name'=>'xxx', 'name'=>'aaa' ], 1=>array [
'student_id'=>'2', 'college_name'=>'yyy', 'name'=>'bbb' ] ] 

请有人帮我得到上面的输出。

2 个答案:

答案 0 :(得分:1)

您可以循环数组并使用array_combine

$column_names= [ 0=>'student_id', 1=>'college_name', 2=>'name' ];

$student_details=[ 0=>[
   0=>'1', 1=>'xxx', 2=>'aaa' ], 1=>[
   0=>'2', 1=>'yyy', 2=>'bbb' ] ];

foreach($student_details as &$sub){
    $sub = array_combine($column_names, $sub);
}
var_dump($student_details);

输出:

array(2) {
  [0]=>
  array(3) {
    ["student_id"]=>
    string(1) "1"
    ["college_name"]=>
    string(3) "xxx"
    ["name"]=>
    string(3) "aaa"
  }
  [1]=>
  &array(3) {
    ["student_id"]=>
    string(1) "2"
    ["college_name"]=>
    string(3) "yyy"
    ["name"]=>
    string(3) "bbb"
  }
}

https://3v4l.org/D9kCE

答案 1 :(得分:0)

尝试一下:-

$column_names = [ 0=>'student_id', 1=>'college_name', 2=>'name' ];

$student_details = [ 
    0=>[0=>'1', 1=>'xxx', 2=>'aaa' ], 
    1=>[0=>'2', 1=>'yyy', 2=>'bbb' ] 
];
$new_array = [];
foreach($student_details as $k=>$val){
     $new_array[$k] =  array_combine($column_names, $val);
}

print_r($new_array);