Create group JSON array from collection.
/**
* Crete group JSON array from collection object.
* Can set fields that will be added to JSON array grouped by field.
*
* @param Varien_Object $collection
* @param array $groupFileds
* @param array $fields
*
* @return JSON array
*/
public function arrayGroupToJson ($ collection , $ groupFileds , $ fields )
{
$ result = array ();
foreach ($ collection as $ item ) {
$ id = array ();
foreach ($ groupFileds as $ field ) {
$ id [] = $ item ->getDataUsingMethod ($ field );
}
$ id = implode ('- ' , $ id );
$ arr = array ();
foreach ($ fields as $ field ) {
$ arr [$ field ] = $ item ->getDataUsingMethod ($ field );
}
if (!isset ($ result [$ id ])) {
$ result [$ id ] = array ();
}
$ result [$ id ][] = $ arr ;
}
return Mage::helper ('core ' )->jsonEncode ($ result );
}
First param some custom or core collection
Second param fields for group, in this example street will be group by city value
Third param fields what will be add into JSON array as one object
echo Mage::helper('yourextension')->arrayGroupToJson(
$collection,
array('city', 'street') ,
array('name', 'position')
);
{
'city1' : {
'street1' : {
'name' : 'Name1' ,
'position' : '0'
} ,
'street2' : {
'name' : 'Name2' ,
'position' : '1'
}
} ,
'city2' : {
'street1' : {
'name' : 'Name1' ,
'position' : '0'
} ,
'street2' : {
'name' : 'Name2' ,
'position' : '1'
} ,
'street3' : {
'name' : 'Name3' ,
'position' : '2'
} ,
'street4' : {
'name' : 'Name4' ,
'position' : '3'
}
}
}