Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active November 23, 2016 13:23
Show Gist options
  • Save evgv/d4065c806dc1fa058b27c62f0bce68fc to your computer and use it in GitHub Desktop.
Save evgv/d4065c806dc1fa058b27c62f0bce68fc to your computer and use it in GitHub Desktop.
Magento. Create group JSON array from collection.

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);
  }
  

How to use:

  • 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')
        );
      

Result:

   {
       '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'
               
           }
       }
   }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment