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);
       }        
    }
 }

しかし、これら2つをマージすると、(基本的に名前とそれに対応するグレードを格納する)目的の出力が得られません。

 $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 に答える