我使用Laravel 5.5
和我有一个返回如下数据的查询(原始查询不是雄辩的)。
多个对象的订单号可以相同(即164377
)。我需要做的是遍历所有结果并为每个订单号创建一个对象(即164377
),而不是为每个ordernumber
创建多个对象。
我无法执行group by
,因为我需要检查每个订单,如果订单号是相同的,我需要操纵一些属性,这只能在我查询所有内容后才能完成
作为来自服务器的JSON
响应返回的数据
{
"ordernumber": 164377,
"deliverydate": "2017-11-28 00:00:00",
"suLN": "60",
"osLN": "1.4",
"osStatus": 100,
"VerifiedOn": null
},
{
"ordernumber": 164377,
"deliverydate": "2017-11-28 00:00:00",
"suLN": "76",
"osLN": "1.4",
"osStatus": 100,
"VerifiedOn": null
},
{
"ordernumber": 164377,
"deliverydate": "2017-11-28 00:00:00",
"suLN": "61",
"osLN": "1.4",
"osStatus": 100,
"VerifiedOn": null
},
{
"ordernumber": 163868,
"deliverydate": "2017-11-08 00:00:00",
"suLN": "94",
"osLN": "3.8",
"osStatus": 1300,
"VerifiedOn": "2017-11-15 06:54:46"
},
控制器
$data = DB
::connection('s2')
->select
("
SELECT
`wo`.`ordernumber`, `wo`.`deliverydate`,
`su`.`ListNumber` as suLN, `os`.`ListNumber` as osLN, `su`.`LineNumber` as suLN, `os`.`LineNumber` as osLN, `os`.`status` as osStatus,
`su`.`VerifiedOn`
FROM
`wo`.`orders` AS `wo`
INNER JOIN
`pr`.`su` AS `su`
ON `wo`.`ordernumber` = `su`.`ordernumber`
INNER JOIN
`pr`.`orderstatus` AS `os`
ON `su`.`FrameNumber` = `os`.`boxnumber`
AND `wo`.`ordernumber` = `os`.`ordernumber`
WHERE
`wo`.`pID` = ?
",
[$pID]
);
foreach ($data as $d) {
// check if object exists or create new object for each $d->ordernumber
// if object exists check if $d->LineNumber matches
// if LineNumber matches
$d->counter = $d->counter + 1; // new property created
}
return response()->json(['data' => $data], 200);
答案 0 :(得分:0)
$new = array(); // Make a new array
foreach ($data as $d) { // Loop over your data
$id = $d->ordernumber; // Get order number for each order
unset($d->ordernumber); // Remove order number from object
$new[$id][] = $d; // Insert object into new array using ordernumber as key
}
print_r($new); // Profit!!
输出是:
Array
(
[164377] => Array
(
[0] => stdClass Object
(
[deliverydate] => 2017-11-28 00:00:00
[suLN] => 60
[osLN] => 1.4
[osStatus] => 100
[VerifiedOn] =>
)
[1] => stdClass Object
(
[deliverydate] => 2017-11-28 00:00:00
[suLN] => 76
[osLN] => 1.4
[osStatus] => 100
[VerifiedOn] =>
)
[2] => stdClass Object
(
[deliverydate] => 2017-11-28 00:00:00
[suLN] => 61
[osLN] => 1.4
[osStatus] => 100
[VerifiedOn] =>
)
)
[163868] => Array
(
[0] => stdClass Object
(
[deliverydate] => 2017-11-08 00:00:00
[suLN] => 94
[osLN] => 3.8
[osStatus] => 1300
[VerifiedOn] => 2017-11-15 06:54:46
)
)
)
现在你可以循环你的新数组了,如果count === 1
只有一个该数字的订单,如果count> 1做你需要做的任何处理。