Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

php - Merge multiple associative arrays to a single array of associative arrays

I have 4 associative arrays as per below:

$ids  = array(
      '0' => '7' ,
      '1' => '8' ,
      '2' => '9'
);
$names = array (
      '0' => 'Name 1' ,
      '1' => 'Name 2' ,
      '2' => 'another name'
);
$marks = array(
      '0' => '8' ,
      '1' => '5' ,
      '2' => '8'
);
§grade = array(
      '0' => '4' ,
      '1' => '2.5' ,
      '2' => '4'
);

I want to "merge" them to a single array, containing associative arrays as per below:

$data = array(
   array(
      'id' => '7' ,
      'name' => 'Name 1' ,
      'marks' => '8',
      'grade' => '4'
   ),
   array(
      'id' => '8' ,
      'name' => 'Name 2' ,
      'marks' => '5',
      'grade' => '2.5'
   ),
   array(
      'id' => '9' ,
      'name' => 'another name',
      'marks' => '8',
      'grade' => '4'
   )
);

I am a new PHP developer and have no idea how to accomplish this. Your help will be much appreciated. Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe this is your array

$ids = array('0' => '7','1' => '8','2' => '9');
$names = array('0' => 'Name 1','1' => 'Name 2','2' => 'another name');
$marks = array('0' => '8','1' => '5','2' => '8');
$grade = array('0' => '4','1' => '2.5','2' => '4');

#New Keys
$keys = array("id","name","marks","grade");

A. You can use MultipleIterator

$final = array();
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($ids));
$mi->attachIterator(new ArrayIterator($names));
$mi->attachIterator(new ArrayIterator($marks));
$mi->attachIterator(new ArrayIterator($grade));

foreach ( $mi as $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);

B. You can use array_map

$final = array();
foreach ( array_map(null, $ids, $names, $marks, $grade) as $key => $value ) {
    $final[] = array_combine($keys, $value);
}
var_dump($final);

Output

array
  0 => 
    array
      'id' => string '7' (length=1)
      'name' => string 'Name 1' (length=6)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)
  1 => 
    array
      'id' => string '8' (length=1)
      'name' => string 'Name 2' (length=6)
      'marks' => string '5' (length=1)
      'grade' => string '2.5' (length=3)
  2 => 
    array
      'id' => string '9' (length=1)
      'name' => string 'another name' (length=12)
      'marks' => string '8' (length=1)
      'grade' => string '4' (length=1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...