匹配php

时间:2018-05-08 07:59:03

标签: php arrays multidimensional-array

我有2个数组$ dizi1和$ dizi2。这些都是这样的。

$dizi1 = [
[
  'id' => 1,
  'name' => 'özkan',
  'surname' => 'özdemir',
],
[
    'id' => 2,
    'name' => 'çağrı',
    'surname' => 'uğurel',
],
[
    'id' => 3,
    'name' => 'can',
    'surname' => 'tokay'
],
[
    'id' => 4,
    'name' => 'lütfü',
    'surname' => 'uzun'
]
];

$dizi2 = [
[
    'id' => 2,
    'birthday' => 1993
],
[
    'id' => 3,
    'birthday' => 1990
],
[
    'id' => 4,
    'birthday' => 1989
],
[
    'id' => 1,
    'birthday' => 1987
]
];

这就是我想要的

istenenDizi = [
[
    'id' => 1,
    'name' => 'özkan',
    'surname' => 'özdemir',
    'birthday' => 1987,
]
];
我很努力地找到一个algortihm来做这件事。我还将创建两个excel表,我将使用它。你能帮帮我怎么办? Thanksss!

2 个答案:

答案 0 :(得分:3)

您可以使用foreach()array_search()array_column(),如下所示: -

$istenenDizi = [];

foreach($dizi1 as $dizi1){

  $istenenDizi[$dizi1['id']] = $dizi1;
  $istenenDizi[$dizi1['id']]['birthday'] = $dizi2[array_search($dizi1['id'],array_column($dizi2,'id'))]['birthday'];
}
$istenenDizi = array_values($istenenDizi);

print_r($istenenDizi);

输出: - https://eval.in/1000838

答案 1 :(得分:2)

当你的第二个数组未排序时,你可以先排序它。然后按项目组合两个数组。 Demo

usort($dizi2, function($a, $b){ return $a['id'] > $b['id'];});
foreach($dizi1 as $k=>$v){
    $v['birthday'] = $dizi2[$k]['birthday'];
    $result[] = $v;
}