[英]How to merge/combine/insert of 2 different arrays based on key value in PHP
[英]How to merge arrays with same value and different key in PHP?
在這里,我想清楚地解釋我的問題。
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
嘗試這個:
<?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] =您的數據
ps,如果要創建新數組,其中數組名稱必須為$ employee_id,例如:$ 0001,則不可能,因為變量名稱必須以字母開頭
// 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',
// ...
)
);
我希望這能幫到您
_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>";
?>
輸出繼電器:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.