循环遍历多维数组并删除重复并合并其他值

时间:2015-07-30 06:43:22

标签: php arrays

我有如下的数组。我想取消设置具有相同q_id的所有数组,但合并其name键。

      array
         0 => 
           array
              'field_name' => string 'Hindu rastrya' (length=13)
              'name' => string '283' (length=3)
              'q_id' => string '199' (length=3)
         1 => 
           array
              'field_name' => string 'dharma nirpachya' (length=16)
              'name' => string '284' (length=3)
              'q_id' => string '199' (length=3)
         2 => 
           array
              'field_name' => string 'j vaye pni hunxa' (length=16)
              'name' => string '285' (length=3)
              'q_id' => string '199' (length=3)
         3 => 
           array
              'field_name' => string 'Nepal' (length=5)
              'name' => string '286' (length=3)
              'q_id' => string '200' (length=3)
         4 => 
           array
              'field_name' => string 'India' (length=5)
              'name' => string '287' (length=3)
              'q_id' => string '200' (length=3)
         5 => 
           array
              'field_name' => string 'China' (length=5)
              'name' => string '288' (length=3)
              'q_id' => string '200' (length=3)

预期:

       array
     0 => 
       array
          'field_name' => string 'Hindu rastrya' (length=13)
          'name' => 
                 array
                     0 => string '283' (length=3)
                     1 => string '284' (length=3)
                     2 => string '285' (length=3)
          'q_id' => string '199' (length=3)
     1 => 
       array
          'field_name' => string 'Nepal' (length=16)
          'name' => 
                 array
                     0 => string '286' (length=3)
                     1 => string '287' (length=3)
                     2 => string '288' (length=3)
          'q_id' => string '200' (length=3)

我尝试使用代码,但它没有保留密钥,因此失败了:

foreach ($form_option_data as $key=>$option)
    {
        if($form_option_data[$key]['q_id'] == $form_option_data[$key+1]['q_id']){
            unset($form_option_data[$key+1]);
        }
    }

1 个答案:

答案 0 :(得分:2)

以下应该做的工作:

$data = ...; //initial array
$result = array();

foreach ($data as $entry) {
  if (!array_key_exists($entry['q_id'], $result)) {
    $result[$entry['q_id']] = array(
      'q_id' => $entry['q_id'],
      'name' => array($entry['name'])
    );
  } else {
    $result[$entry['q_id']]['name'][] = $entry['name'];
  }
}

$result = array_values($result); // to re-index the table so that keys start from 0