'srcKey' take data.srcKey and set to result.dstKey * 'dstKey' => [ * 'from' => 'srcKey', * 'to' => 'dstKey', * 'filter' => callable, * 'callback' => callable, * 'default' => mixed * ] */ public static function map(array $data, array $map) { $result = array(); foreach ($map as $dstKey => $info) { $srcKey = null; $filter = null; $callback = null; $default = null; if (is_array($info)) { $dstKey = (isset($info['to'])) ? $info['to'] : $dstKey; $srcKey = (isset($info['from'])) ? $info['from'] : $dstKey; $filter = (isset($info['filter'])) ? $info['filter'] : null; $callback = (isset($info['callback'])) ? $info['callback'] : null; $default = (isset($info['default'])) ? $info['default'] : null; } else { $srcKey = $info; $dstKey = is_int($dstKey) ? $srcKey : $dstKey; } if (is_array($srcKey) || (is_string($srcKey) && false !== strpos($srcKey, '.'))) { $value = static::get($data, $srcKey, $default); } else { $value = array_key_exists($srcKey, $data) ? $data[$srcKey] : $default; } if (null !== $value && null !== $filter) { $value = call_user_func($filter, $value); } if (null !== $callback) { $value = call_user_func($callback, $value, $srcKey, $data); } $result[$dstKey] = $value; } return $result; } /** * @param array|\ArrayAccess $source * @param string|array $field * @param mixed $default * * @throws \Exception * @return mixed */ public static function get($source, $field, $default = null) { if (!is_array($source) && !$source instanceof ArrayAccess) { throw new Exception('param $source expected to be array or ArrayAccess but found ' . gettype($source)); } if (null === $field) { return $source; } $parts = is_array($field) ? $field : explode('.', $field); foreach ($parts as $name) { if (array_key_exists($name, $source)) { $source = $source[$name]; } else { return $default; } } return $source; } /** * @param array $list * @param array $groupFields * * @return array * * Example: * * $source = [ * ['key1' => 'a', key2 => 'd', 'id' => 1, 'title' => 'first'], * ['key1' => 'a', key2 => 'e', 'id' => 2, 'title' => 'second'], * ['key1' => 'b', key2 => 'f', 'id' => 3, 'title' => 'third'], * ['key1' => 'b', key2 => 'f', 'id' => 4, 'title' => 'fourth'], * ]; * * $result = Data::group($source, ['key1', 'key2']); * * $result => [ * 'a' => [ * 'key1' => 'a', * 'key1' => 'd', * 'list' => [['id' => 1, 'title' => 'first'], ['id' => 2, 'title' => 'second']] * ], * 'b' => [ * 'key1' => 'b', * 'key1' => 'f', * 'list' => [['id' => 3, 'title' => 'third'], ['id'] => 4, 'title' => 'fourth'] * ], * ] * */ public static function group(array $list, array $groupFields) { $result = []; $groupKey = reset($groupFields); $groupTpl = array_fill_keys($groupFields, null); foreach ($list as $row) { $group = $row[$groupKey]; if (!array_key_exists($group, $result)) { $result[$group] = array_intersect_key($row, $groupTpl); } $result[$group]['list'][] = array_diff_key($row, $groupTpl); } return $result; } }