如何在PHP中合并具有相同值和不同键的数组?

时间:2015-06-09 07:50:58

标签: php arrays

我想清楚地解释一下我的问题。

id  company ID  Employee ID Name        Relationship    Dob     Age Gender       
1   EMPL        00001       Choodamani  Spouse      11-Aug-66   49  Female            
2   EMPL        00001       Komala      Mother      30-Oct-39   76  Female            
3   EMPL        00001       Varshini    Daughter    29-Apr-04   11  Female            
4   EMPL        00001       Vasudevan   Employee    15-Jul-62   53  Male    
5   EMPL        00002       Siddharth   Son         1-Jun-00    15  Male              
6   EMPL        00002       Poongavanam Mother      21-Oct-39   76  Female            
7   EMPL        00002       Aruna       Spouse      16-Sep-68   47  Female            
8   EMPL        00002       Abirami     Daughter    7-May-97    18  Female            
9   EMPL        00002       Murali      Employee    7-Oct-67    48  Male    

在这里你可以看到一张表,这张表是我从我的数据库中获取的。在此数据中,您可以看到employee_id对于前四行是相同的,但每行的id不同。这里我需要在一个数组中合并相同的employee_id。

示例:一个数组中的所有00001 employee_id

3 个答案:

答案 0 :(得分:1)

试试这个:

<?php 
  $new_sort = array();
  foreach ($db_array as $db_row){
    $key_row = $db_row["Employee_ID"];
    unset($db_row["Employee_ID"]);
    $new_sort[$key_row][] = $db_row;
  }
?>
输出

你将有嵌套数组,其中$ new_sort [some_employee_id] =你的数据

p.s如果你想创建一个新的数组,其中数组的名称必须是$ employee_id,例如:$ 0001,这是不可能的,因为变量名必须以字母开头

答案 1 :(得分:0)

// Assuming your data is available in an associative array ($_data):
$employees = array();
foreach($_data as $employee) {
    $id = $employee['Employee ID'];
    if(isset($employees[$id])) {
        $employees[$id][] = $employee;
    } else {
        $employees[$id] = array($employee);
    }
}

// The results are now grouped, so:
$employees['00001'] = array(
    array(
        'Name' => 'Choodamani',
        // ...
    ),
    array(
        'Name' => 'Komala',
        // ...
    )
);

答案 2 :(得分:0)

我希望这会对你有所帮助

_form.php这个

<?php

class Claim
 {
      public function Arraycombine($keys, $values)
      {
         $result = array();
         foreach ($keys as $i => $k) {
           $result[$k][] = $values[$i];
         }
         array_walk($result, create_function('&$v', '$v = (count($v) == 1)?        array_pop($v): $v;'));
         return    $result;
         } 

    }

    $data1 = ArrayHelper::map(Employee::find()->all(), 'id', 'employee_id');
    $data2 = ArrayHelper::map(Employee::find()->all(), 'id', 'name');

    $claim = new Claim();

    $claimers = $claim->Arraycombine( $data1, $data2 );

    echo "<pre>"; print_r($claimers);exit(); echo "</pre>";

?>

输出中:

enter image description here