2017-06-22 63 views
0

我有對象的數組作爲檢查是否存在鍵值中的任何對象的數組(對象數組)

$a = [{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}]; 

在這裏,我想創建下賤的新數組,其中重複的對象不會在那裏( invoice_id),因爲新陣列將具有相同的第一個對象invoice_id。我是這樣做的。

foreach ($a as $key => $value) { 
     if(isset($new)) { 
      foreach ($new as $k => $val) { 
       if($val->id != $value->id) { 
        $new[] = $value; 
       } 
      } 
     }else{ 
      $new[] = $value; 
     } 
    } 

我的新陣列將像

$new = [{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}] 

,但它是不是給所需的輸出。應該做什麼 ?

+0

什麼是'$ new'? – Nawin

+0

$ new將是新陣列 – JohnB

回答

3

既然您已將此標記爲Laravel問題,請使用collections

較少的代碼(一行!)和性能命中不存在。

$a = json_decode('[{"id":"20","invoice_id":"123"},{"id":"21","invoice_id":"123"},{"id":"22","invoice_id":"125"},{"id":"23","invoice_id":"125"},{"id":"24","invoice_id":"123"}]'); 

$result = collect($a)->groupBy('invoice_id'); 

後OP編輯問題:

$result = collect($a)->unique('invoice_id')->values()->toArray(); 

結果:

=> [ 
    {#826 
     +"id": "20", 
     +"invoice_id": "123", 
    }, 
    {#824 
     +"id": "22", 
     +"invoice_id": "125", 
    }, 
    ] 

,或者使用->toJson()代替->toArray()

"[{"id":"20","invoice_id":"123"},{"id":"22","invoice_id":"125"}]" 
+0

我不明白您的意見。 – Kyslik

+0

對不起,但這不是結果我desire.thanks – JohnB

+0

編輯後:使用' - > unique('invoice_id')'而不是'groupBy',你可以通過' - > toArray()將其轉換爲數組' – Kyslik

0
$result = []; 
foreach ($a as $data) { 
    $result[$data->id] = $data; 
} 

var_dump(array_values($results)); 
+0

它正在採取排或對象的最後ocuurence – JohnB

1

請嘗試下面的代碼用簡單的邏輯,

$temp = $new = array(); 
$b = json_decode($a, true); 
foreach ($b as $key => $val) { 
    if(!in_array($val['invoice_id'], $temp)) { 
    $temp[$val['id']] = $val['invoice_id']; 
    $new[] = array('id' => $val['id'], 'invoice_id' => $val['invoice_id']); 
    } 
} 

print_r($new); 

我只是創建一個臨時數組僅存儲唯一INVOICE_ID在一個循環比較。

它給下面的結果,

Array 
(
    [0] => Array 
    (
     [id] => 20 
     [invoice_id] => 123 
    ) 

    [1] => Array 
    (
     [id] => 22 
     [invoice_id] => 125 
    ) 

) 
0

試試這個

$a = json_decode($a); 

$invoiceid = []; 
$unique = []; 
foreach ($a as $key => $value) { 
    if(!in_array($value->invoice_id,$invoiceid)) { 
     $invoiceid[] = $value->invoice_id; 
     $unique[] = $value; 
    } 

} 
    echo $a = json_encode($unique); 
相關問題