I have 30 JSON objects inside an array. I would like to loop through each object and create a new Array of only 3 objects containing data of 10 objects each.
My issue here is I am not sure how to create new objects while in a foreach loop
Example:
keys on the left and value on the right
1 1
2 2
3 3
. .
. .
. .
1 11
1 12
2 13
. .
. .
. .
1 21
2 22
3 23
. .
. .
Here, sid tells what all objects needs to be grouped into a single object, as per this example group 10 objects into 1.
so currently I have :
[
{
"key1" : "value1",
"key2" : "value2",
"sid" : "1"
},
{
"key1" : "value3",
"key2" : "value4",
"sid" : "1"
},
.
. // Total 10 objects with sid = 1
.
,
{
"key1" : "value5",
"key2" : "value6",
"sid" : "2"
},
{
"key1" : "value7",
"key2" : "value8",
"sid" : "2"
},
.
. // Total 10 objects with sid = 2
.
,
{
"key1" : "value9",
"key2" : "value10",
"sid" : "3"
},
{
"key1" : "value11",
"key2" : "value12",
"sid" : "3"
},
.
. // Total 10 objects with sid = 3
]
I would like to replace it as:
[
{
"value2" : "value1",
"value4" : "value3", //all data in this object belongs to sid = 1
"valueN" : "valueM" //Other respective 8 objects
},
{
"value6" : "value5",
"value8" : "value7", //all data in this object belongs to sid = 2
"valueN" : "valueM" //Other respective 8 objects
},
{
"value10" : "value9",
"value12" : "value11", //all data in this object belongs to sid = 3
"valueN" : "valueM" //Other respective 8 objects
}
]
code
I am directly loop through each and every object inside an array and adding them into new array called finalResult by setting key as value of the key2 and value as key1 value
for ($i = 0; $i < $count; $i++)
{
$finalResult[$arrObj[$i]['key2']] = $arrObj[$i]['key1'];
}
This only creates a single object with all data in it.
I would like to do some check if sid == 11,12,13,... and so on then create new object and start adding all the data inside newly created object until next sid is encountered.
Update
This is what I got:
{
"1": {
"value2" : "value1",
"value4" : "value3",
"valueN" : "valueM" //Other respective 8 objects
},
"2": {
"value6" : "value5",
"value8" : "value7",
"valueN" : "valueM" //Other respective 8 objects
},
"3": {
"value10" : "value9",
"value12" : "value11",
"valueN" : "valueM" //Other respective 8 objects
}
}
I was expecting :
[
{
"value2" : "value1",
"value4" : "value3",
"valueN" : "valueM" //Other respective 8 objects
},
{
"value6" : "value5",
"value8" : "value7",
"valueN" : "valueM" //Other respective 8 objects
},
{
"value10" : "value9",
"value12" : "value11",
"valueN" : "valueM" //Other respective 8 objects
}
]