I have an Array with this structure
3 => {#631 ▼
+"id": 20
+"cliente": "Juan Pérez"
+"codigo": "01/A2"
}
4 => {#1038 ▼
+"id": 20
+"cliente": "Juan Pérez"
+"codigo": "01/A3"
}
5 => {#1249 ▼
+"id": 20
+"cliente": "Juan Pérez"
+"codigo": "01/A1"
}
6 => {#1248 ▼
+"id": 19
+"cliente": "Autoescuelas Perez S.L"
+"codigo": "01/A3"
}
7 => {#1251 ▼
+"id": 19
+"cliente": "Autoescuelas Perez S.L"
+"codigo": "01/A1"
}
8 => {#1252 ▼
+"id": 19
+"cliente": "Autoescuelas Perez S.L"
+"codigo": "01/A2"
}
9 => {#1253 ▼
+"id": 18
+"cliente": "bfsfdgsdfg"
+"codigo": "01/A2"
}
I need to transform it into this:
3 => {#631 ▼
+"id": 20
+"cliente": "Juan Pérez"
+"codigo": "01/A2,01/A3,01/A1"
}
6 => {#1248 ▼
+"id": 19
+"cliente": "Autoescuelas Perez S.L"
+"codigo": "01/A2,01/A3,01/A1"
}
9 => {#1253 ▼
+"id": 18
+"cliente": "bfsfdgsdfg"
+"codigo": "01/A2"
}
I've tried several things but none of them worked fairly well or even worked, what's more I don't even know how to do it the truth because if you make a loop to the same id and extract the code part, use the + operator to join the two codes it didn't work for me So I really don't know how to deal with this. I have tried this:
$ite=0;
for ($i=0; $i <count($ventas) ; $i++) {
if ($ite < count($ventas)-1) {
$ite++;
}
if ($ventas[$i]->id==$ventas[$ite]->id) {
$ventas[$i]->codigo=$ventas[$i]->codigo." ".$ventas[$ite]->codigo;
}
}
But it's not even remotely close to what I need
You can do grouping easily if you use the grouper (client id) as the key of an array. The important thing is to check the existence of the key to decide between initializing or adding:
Here the recommendation is to handle the codes as an array instead of a comma separated list. If required, at any time it is easy to do
implode(',', $ventas[6]->codigos)
.An example of the result for client 20 would be:
If the original key (
primerId
) is disposable, the following code is not needed to reassign:The end result should be something like this:
I can think of 3 ways to solve it:
1.- Detect the odd ones through an if
2.- Create an if that saves the ids, and compare them in each round and validate that it is different from
3.- In your query order with an ORDER BY ID ASC/DESC and add a DISTINCT id to order the values and remove your duplicates
This would be an example since I don't know what your complete structure is like, simulate the values to obtain the odd ones
https://paiza.io/projects/LeuyO6y_dcGFLzP8JbDBlg
The most recommended is to use the DISTINCT since it is easier, otherwise the next thing is to create the if and take the unique ids avoiding the duplicates, to maintain the consistency of the data, and the part of the odd ones can vary, you would have to analyze if in your odd ones, more duplicates may come, it is not highly recommended, but analyze and try to adapt any of these solutions