I am going to get results from database like this.
array(
[0] => array(
[type] => orange,
[number] => 10,
[size] => 10c,
[weight] => 1l
)
[1] => array(
[type] => mango,
[number] => 10,
[size] => 10c,
[weight] => 1l
)
[1] => array(
[type] => apple,
[number] => 10,
[size] => 10c,
[weight] => 1l
)
[3] => array(
[type] => mango,
[number] => 10,
[size] => 10c,
[weight] => 1l
)
)
Basically, I need to convert this to the following JSON Format:
"mango" : [{
"number" : "10",
"size" : "10c",
"weight" : "1l"
},
{
"number" : "12",
"size" : "14c",
"weight" : "12"
}
],
"orange" : [{
"number" : "12",
"size" : "10c",
"weight" : "1l"
},
{
"number" : "12",
"size" : "14c",
"weight" : "11"
}
],
"apple" : [{
"number" : "10",
"size" : "10c",
"weight" : "1l"
},
{
]
Ignore the number, size and weight. Those are just random numbers. But the first element in the array contains the JSON tag. That should be removed from the array, but taken as tag for array of objects in JSON (you can see that).
I know we can write with loops, conditions, etc. Is there a smart and quick way to do this with existing built in php functions with less looping and conditions?
I guess, these are the steps:
- Filter the arrays individuality based on type. Probably, 3 times here to get the 3 fruits. Which function would help here? Filter based on Value. Or ideally key value pair.
- You get 3 arrays, each for one type of fruit. Pop off the type element in all arrays individually.
- Loop through the types, and put the arrays in each type, with type value as index.
Any other better ways?