2017-08-12 1 views
0

私はループから次の2つのstdClass配列を持っています。今私はキー 'id'が一致するときにそれらをマージする必要があります。PHPで2つのstdClassオブジェクト配列をマージ

array (size=1) 
    0 => 
    object(stdClass)[28] 
     public 'id' => string '78' (length=2) 
     public 'quantity' => string '5' (length=1) 




array (size=1) 
    1 => 
    object(stdClass)[31] 
     public 'product_id' => string '78' (length=2) 
     public 'quantity' => string '1' (length=1) 

ので、最終的な配列は

array (size=1) 
    1 => 
    object(stdClass)[31] 
     public 'product_id' => string '78' (length=2) 
     public 'quantity' => string '6' (length=1) 

それを行う方法上の任意の助けになりますか?私はjson_decodeを使って元のデータをデコードします。このフォーマットのデータは[{"id":"78","quantity":"1"}]です。

+0

array1とarray2はデータベースの結果セットですか?あなたは最初の配列をループし、2番目の配列をマップしようとしましたか? – DanielO

+0

はい、データベース結果セットです。それらは基本的にデータベースに直列化された文字列で、引き出されるときにはjson_decodeです。彼らは同じループのものです。 –

答えて

0

json_decodeに追加のパラメータを追加すると、データを連想配列として取得することができます。これは、操作がはるかに簡単です。私はいくつかのバージョン(最初はPHP 7です)を行い、あなたのシステムで動作するものを選んでください。

<?php 
error_reporting (E_ALL); 
ini_set ('display_errors', 1); 

$arr1 = json_decode('[{"id":"78","quantity":"1"}, {"id":"79","quantity":"3"}]', true); 
$arr2 = json_decode('[{"id":"78","quantity":"5"}]', true); 

$arr3 = array_merge($arr1, $arr2); 

// V7 
$result = []; 
foreach ($arr3 as $element) { 
    $result[$element['id']] = ($result[$element['id']]??0) 
       + $element['quantity']; 
} 

print_r($result); 
// Prior to V7 
$result = array(); 
foreach ($arr3 as $element) { 
    if (!isset($result[$element['id']])){ 
     $result[$element['id']] = 0; 
    } 
    $result[$element['id']] += $element['quantity']; 
} 

print_r($result); 

私はこれが合算方法を示すために別の要素を追加しましたが、これの出力がある...

Array 
(
    [78] => 6 
    [79] => 3 
) 
Array 
(
    [78] => 6 
    [79] => 3 
) 
+0

完璧なソリューション。ありがとう! –

0

ここでは、あなたの元の質問にフォーマットを維持ソリューションです。 配列を処理する簡潔な方法であるarray_reduceも使用します。

<?php 
$input1 = '[{"id":"78","quantity":"7800"}, 
    {"id":"79","quantity":"7900"}, 
    {"id":"80","quantity":"8000"}]'; 
$input2 = '[{"id":"78","quantity":"6"}, 
    {"id":"79","quantity":"8"}, 
    {"id":"80","quantity":"6"}, 
    {"id":"81","quantity":"7"}]'; 

$input1Arr = json_decode($input1); 
$input2Arr = json_decode($input2); 

$combinedArrays = array_merge($input1Arr, $input2Arr); 

echo "combinedArrays = " . print_r($combinedArrays, true) . "\n"; 

$result = array_reduce($combinedArrays, 
    function($intermediateResult, $item){ 
     if (! array_key_exists($item->id, $intermediateResult)) { 
      // First time encountering an object with this id 
      $intermediateResult[$item->id] = $item; 
     } 
     else { 
      // We have an object with this id already so just add the quantity 
      $intermediateResult[$item->id]->quantity += $item->quantity; 
     } 
     return $intermediateResult; 
    }, []); 
// Get the values from the result array 
print_r(array_values($result)); 
+0

チャームのように働いた。ありがとう! –

関連する問題