我有一个对象数组
$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"}];
这里我想创建一个新的abject数组,其中重复的对象不会存在(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 :(得分: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"}]"
答案 1 :(得分: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
)
)
答案 2 :(得分:0)
$result = [];
foreach ($a as $data) {
$result[$data->id] = $data;
}
var_dump(array_values($results));
答案 3 :(得分: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);