1

我有以下多维数组:

$record = Array(
  Array("name" => "Sheila", "exam1" => "90", "exam2" => "80", "exam3" => "85"),
  Array("name" => "Peter", "exam1" => "80", "exam2" => "95", "exam3" => "85"),
  Array("name" => "Konrad", "exam1" => "98", "exam2" => "70", "exam3" => "89") 
);

我一直在使用以下代码,

 foreach ( $record as $student ) {
    // store exam # 1 
    foreach ( $student as  $name => $value ) {
       if ( $name == "name") {
          $name = Array ($name => $value);
       }

       if ( $name == "exam1") {
          $grade = Array ($name => $value);
       }        
    }
 }

但是当我合并这两个时,我没有得到我想要的输出(基本上存储名称及其相应的等级):

 $exam1 = Array( 
  Array("name" => "Sheila", "exam1" => "90"),
  Array("name" => "Peter", "exam1" => "80"),
  Array("name" => "Konrad", "exam1" => "98")
 ); 

如何获得我想要的数组?

4

1 回答 1

1
$data = array();
foreach($students as $record) {
  $data[] = array('name' => $record['name'], 'exam1' => $record['exam1']);
}

或者您可以使用更高级(且更易于扩展)的版本:

<?php
$students = Array(
  Array("name" => "Sheila", "exam1" => "90", "exam2" => "80", "exam3" => "85"),
  Array("name" => "Peter", "exam1" => "80", "exam2" => "95", "exam3" => "85"),
  Array("name" => "Konrad", "exam1" => "98", "exam2" => "70", "exam3" => "89") 
);

$desired_metadata = array('name', 'exam1');
$data = array();
$flip = array_flip($desired_metadata);
foreach($students as $record) {
    $data[] = array_combine($desired_metadata, array_intersect_key($flip, $record));
}

var_dump($data);
于 2012-11-24T14:30:08.613 回答