首页 > 解决方案 > 将 2 个数组与特定元素合并

问题描述

假设我有 2 个这样的数组

数组问题:

array (size=4)
  0 => 
    array (size=2)
      'id' => string '4'
      'question' => string 'what food do you like?'
  1 => 
    array (size=2)
      'id' => string '5'
      'question' => string 'where do you want to go?'
  2 => 
    array (size=2)
      'id' => string '6'
      'question' => string 'are you busy?'
  3 => 
    array (size=2)
      'id' => string '7'
      'question' => string 'are you enjoy the party?'

第二个数组是答案数组:

array (size=3)
  0 => 
    array (size=2)
      'id' => string '4'
      'answer' => string 'burger'
  1 => 
    array (size=2)
      'id' => string '5'
      'answer' => string 'go to mall'
  2 => 
    array (size=2)
      'id' => string '6'
      'answer' => string 'no im not'

我如何合并这 2 个数组变成这样

id : 4
question : 'what food do you like?'
answer : 'burger'

id : 5
question : 'where do you want to go?'
answer : 'go to mall'

id : 6
question : 'are you busy?'
answer : 'no im not'

id : 7
question : 'are you enjoy the party?'
answer : ''

如果它不能回答某些问题,我需要添加答案''(emtpy)。我如何合并该数组

标签: phparrays

解决方案


此代码将为您提供所需的结果。对于每个问题,它会查看答案数组中是否有答案。如果有,它会推送 id、问题和答案,否则它只是将 id 和问题以及空白答案推送到结果数组中。请注意,它使用了一些偏执的代码(array_combine在 的键和值上使用$answers),但这意味着它的工作原理与$questions和中的值的顺序无关$answers

$questions = array (
    array (
      'id' =>  '4',
      'question' =>  'what food do you like?'),
    array (
      'id' =>  '6',
      'question' =>  'are you busy?'),
    array (
      'id' =>  '5',
      'question' =>  'where do you want to go?'),
    array (
      'id' =>  '7',
      'question' =>  'are you enjoy the party?')
    );

$answers = array (
    array (
      'id' =>  '6',
      'answer' =>  'no im not'),
    array (
      'id' =>  '4',
      'answer' =>  'burger'),
    array (
      'id' =>  '5',
      'answer' =>  'go to mall')
    );

$qanda = array();
foreach ($questions as $question) {
    $id = $question['id'];
    $akey = array_search($id, array_combine(array_keys($answers), array_column($answers, 'id')));
    $qanda[] = array('id' => $id,
                     'question' => $question['question'],
                     'answer' => ($akey !== false) ? $answers[$akey]['answer'] : '');
}
print_r($qanda);

输出:

Array
(
    [0] => Array
        (
            [id] => 4
            [question] => what food do you like?
            [answer] => burger
        )

    [1] => Array
        (
            [id] => 5
            [question] => where do you want to go?
            [answer] => go to mall
        )

    [2] => Array
        (
            [id] => 6
            [question] => are you busy?
            [answer] => no im not
        )

    [3] => Array
        (
            [id] => 7
            [question] => are you enjoy the party?
            [answer] => 
        )

)

推荐阅读