same - php object merge




PHP通過值為2個不同的數組值來合併數組 (4)

未經測試,但這應該工作,或至少讓你關閉。

for ($array1 as $key1 => $value1) {
    for ($array2 as $key2 => $value2) {
        if ($value1['rank'] == $value2['rank']) {
            $result[$key1] = [$value2['size'], $value1['rank'], $value1['id']];
        };
    };
};

我試圖將兩個不同的數組合併成一個數組。 任何人都可以幫我嗎?

我有這樣的數組

[0] (Array)#2
  [rank] "579"
  [id] "1"
[1] (Array)#4
  [rank] "251"
  [id] "2"

[0] (Array)#2
  [size] "S"
  [rank] "251"
[1] (Array)#15
  [size] "L"
  [rank] "579"

我需要這個

[0] (Array)#2
  [size] "S"
  [rank] "251"
  [id] "1"
[1] (Array)#15
  [size] "L"
  [rank] "579"
  [id] "1"

看你提供的數組,我假設你想使用關鍵的排名作為加入點(這似乎不是一個好主意,問題將是如果他們獨特或不),如果他們是獨特的,然後一個微小的方法可以幫助基於他們的排名獲取元素,其餘的只是匯集結果:

<?php

$arr1 = [
    [
        'rank' => 579,
        'id' => 1
    ],
    [
        'rank' => 251,
        'id' => 2
    ],
];

$arr2 = [
    [
        'size' => 'S',
        'rank' => 251
    ],
    [
        'size' => 'L',
        'rank' => 579
    ],
];

function getItemByRank($array, $rank)
{
    foreach ($array as $item){
        if ($item['rank'] === $rank) {
            return $item;
        }
    }
}


$result = [];
foreach ($arr1 as $k => $item) {

    $match = getItemByRank($arr2, $item['rank']);

    if (isset($match)) {
        $result[$k] = $item;
        $result[$k]['size'] = $match['size'];
    }
}

print_r($result);

輸出:

Array
(
    [0] => Array
        (
            [rank] => 579
            [id] => 1
            [size] => L
        )

    [1] => Array
        (
            [rank] => 251
            [id] => 2
            [size] => S
        )

)

//save keys of ranks in the 1st array
$keys = array(); 
foreach($arr1 as $k => $v)
   $keys[$v['rank']] = $k;

$res = array();
// Walk through the 2nd array and make result
foreach($arr2 as $k => $v) 
 if (isset($keys[$v['rank']])) 
    $res[] = array_merge($arr1[$keys[$v['rank']]], $v);

print_r($res);

foreach($arr1 as $key1 => $data1){
    foreach($arr2 as $key2 => $data2){
        if($data1['rank']==$data2['rank']){
            $result[] = array_merge($data1, $data2);
        }
    }
}
print_r($result);




merge