Рубрики
Uncategorized

Пример определения и использования библиотеки классов операционных массивов, реализованной в PHP

Автор оригинала: David Wong.

В этой статье описывается определение и использование библиотеки классов операционного массива, реализованной в PHP. Поделитесь для вашей справки следующим образом:

Библиотеки классов (полные библиотеки классов):

php
class ArrayHelper{
  /**
   * Delete blank elements from an array (including elements with only blank characters)
   *
   * Usage:
   * @code php
   * $arr = array('', 'test', '  ');
   * ArrayHelper::removeEmpty($arr);
   *
   * dump($arr);
   *// There will be only'test'in the output.
   * @endcode
   *
   *@ Array to be processed by param array $arr
   *@ Whether param Boolean $trim calls trim functions on array elements
   */
  static function removeEmpty(& $arr, $trim = TRUE)
  {
    foreach ($arr as $key => $value)
    {
      if (is_array($value))
      {
        self::removeEmpty($arr[$key]);
      }
      else
      {
        $value = trim($value);
        if ($value == '')
        {
          unset($arr[$key]);
        }
        elseif ($trim)
        {
          $arr[$key] = $value;
        }
      }
    }
  }
  /**
   * Returns all values of the specified key from a two-dimensional array
   *
   * Usage:
   * @code php
   * $rows = array(
   *   array('id' => 1, 'value' => '1-1'),
   *   array('id' => 2, 'value' => '2-1'),
   * );
   * $values = ArrayHelper::getCols($rows, 'value');
   *
   * dump($values);
   *// The output is
   *  // array(
   *  //  '1-1',
   *  //  '2-1',
   *  // )
   * @endcode
   *
   *@ Param array $arr data source
   *@ Key to query for param string $col
   *
   *@ An array containing all the values of the specified key
   */
  static function getCols($arr, $col)
  {
    $ret = array();
    foreach ($arr as $row)
    {
      if (isset($row[$col])) {
        $ret[] = $row[$col];
      }
    }
    return $ret;
  }
  /**
   * Convert a two-dimensional array to HashMap and return the result
   *
   * Usage 1:
   * @code php
   * $rows = array(
   *   array('id' => 1, 'value' => '1-1'),
   *   array('id' => 2, 'value' => '2-1'),
   * );
   * $hashmap = ArrayHelper::toHashmap($rows, 'id', 'value');
   *
   * dump($hashmap);
   *// The output is
   *  // array(
   *  //  1 => '1-1',
   *  //  2 => '2-1',
   *  // )
   * @endcode
   *
   * If the $valueField parameter is omitted, each item of the transformation result is an array containing all the data for that item.
   *
   * Usage 2:
   * @code php
   * $rows = array(
   *   array('id' => 1, 'value' => '1-1'),
   *   array('id' => 2, 'value' => '2-1'),
   * );
   * $hashmap = ArrayHelper::toHashmap($rows, 'id');
   *
   * dump($hashmap);
   *// The output is
   *  // array(
   *  //  1 => array('id' => 1, 'value' => '1-1'),
   *  //  2 => array('id' => 2, 'value' => '2-1'),
   *  // )
   * @endcode
   *
   *@ Param array $arr data source
   *@ Param string $keyfield converts by what key's value
   *@ Key values corresponding to param string $valueField
   *
   *@ return array converted HashMap style array
   */
  static function toHashmap($arr, $keyField, $valueField = NULL)
  {
    $ret = array();
    if ($valueField)
    {
      foreach ($arr as $row)
      {
        $ret[$row[$keyField]] = $row[$valueField];
      }
    }
    else
    {
      foreach ($arr as $row)
      {
        $ret[$row[$keyField]] = $row;
      }
    }
    return $ret;
  }
  /**
   * Grouping a two-dimensional array by the value of the specified field
   *
   * Usage:
   * @endcode
   *
   *@ Param array $arr data source
   *@ Param string $keyfield as the key name for grouping
   *
   *@ Result after return array grouping
   */
  static function groupBy($arr, $keyField)
  {
    $ret = array();
    foreach ($arr as $row)
    {
      $key = $row[$keyField];
      $ret[$key][] = $row;
    }
    return $ret;
  }
  /**
   * Converts a planar two-dimensional array to a tree structure according to the specified field
   *
   *
   * If you want to get a subtree whose root is any node, you can use the $refs parameter:
   * @code php
   * $refs = null;
   * $tree = ArrayHelper::tree($rows, 'id', 'parent', 'nodes', $refs);
   *
   *// Node with output ID of 3 and all its sub-nodes
   * $id = 3;
   * dump($refs[$id]);
   * @endcode
   *
   *@ Param array $arr data source
   *@ Param string $keyNodeId node ID field name
   *@ Param string $keyParentId node parent ID field name
   *@ Param string $keyChildrens saves the field name of the child node
   *@ Does param Boolean $refs include node references in the return result
   *
   * Array of return array tree structure
   */
  static function toTree($arr, $keyNodeId, $keyParentId = 'parent_id', $keyChildrens = 'childrens', & $refs = NULL)
  {
    $refs = array();
    foreach ($arr as $offset => $row)
    {
      $arr[$offset][$keyChildrens] = array();
      $refs[$row[$keyNodeId]] =& $arr[$offset];
    }
    $tree = array();
    foreach ($arr as $offset => $row)
    {
      $parentId = $row[$keyParentId];
      if ($parentId)
      {
        if (!isset($refs[$parentId]))
        {
          $tree[] =& $arr[$offset];
          continue;
        }
        $parent =& $refs[$parentId];
        $parent[$keyChildrens][] =& $arr[$offset];
      }
      else
      {
        $tree[] =& $arr[$offset];
      }
    }
    return $tree;
  }
  /**
   * Expansion of tree arrays into planar arrays
   *
   * This method is the reverse operation of the tree () method.
   *
   *@ Param array $tree tree tree array
   *@ Param string $keyChildrens contains the key name of the child node
   *
   *@ An array after the return array expansion
   */
  static function treeToArray($tree, $keyChildrens = 'childrens')
  {
    $ret = array();
    if (isset($tree[$keyChildrens]) && is_array($tree[$keyChildrens]))
    {
      foreach ($tree[$keyChildrens] as $child)
      {
        $ret = array_merge($ret, self::treeToArray($child, $keyChildrens));
      }
      unset($node[$keyChildrens]);
      $ret[] = $tree;
    }
    else
    {
      $ret[] = $tree;
    }
    return $ret;
  }
  /**
   * Sort arrays by specified keys
   *
   * @endcode
   *
   *@ Array to be sorted by param array $array
   *@ Key sorted by param string $keyname
   *@ Param int $dir sort direction
   *
   *@ return array sorted array
   */
  static function sortByCol($array, $keyname, $dir = SORT_ASC)
  {
    return self::sortByMultiCols($array, array($keyname => $dir));
  }
  /**
   * Sort a two-dimensional array by multiple columns, similar to ORDER BY in SQL statements
   *
   * Usage:
   * @code php
   * $rows = ArrayHelper::sortByMultiCols($rows, array(
   *   'parent' => SORT_ASC,
   *   'name' => SORT_DESC,
   * ));
   * @endcode
   *
   *@ Array to be sorted by param array $rowset
   *@ The key of param array $args sort
   *
   *@ return array sorted array
   */
  static function sortByMultiCols($rowset, $args)
  {
    $sortArray = array();
    $sortRule = '';
    foreach ($args as $sortField => $sortDir)
    {
      foreach ($rowset as $offset => $row)
      {
        $sortArray[$sortField][$offset] = $row[$sortField];
      }
      $sortRule .= '$sortArray[\'\' . $sortField .\'\'], ' . $sortDir . ', ';
    }
    if (empty($sortArray) || empty($sortRule)) {
      return $rowset;
    }
    eval('array_multisort(' . $sortRule . '$rowset);');
    return $rowset;
  }
}
?>

Примеры использования:

Удаление пустых элементов из массива (включая элементы, содержащие только пустые символы)

Использование:

$arr = array('', 'test', '  ');
ArrayHelper::removeEmpty($arr);
var_dump($arr);

В выводе будет только “тест”.

массив(1) { [1]=> строка(4) “тест” }

Больше читателей, интересующихся контентом, связанным с PHP, могут ознакомиться с темами этого сайта: Навыки работы с массивами PHP, Краткое изложение алгоритмов сортировки Php, Учебник по структуре и алгоритмам данных PHP, Краткое изложение алгоритмов программирования Php, Краткое изложение использования строк Php и Краткое изложение алгоритмов и методов обхода PHP.

Я надеюсь, что эта статья будет полезна для разработки PHP – программ для всех.