Skip to content

Instantly share code, notes, and snippets.

@Norcoen
Created November 27, 2015 12:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Norcoen/1405ec110f87d330c76d to your computer and use it in GitHub Desktop.
Save Norcoen/1405ec110f87d330c76d to your computer and use it in GitHub Desktop.
php function that Recursively converts nested array into a flat one with preserved keys connected with connector.
<?php
/**
* Recursively converts nested array into a flat one with keys preserving.
* @param array $result Resulting array
* @param array $array Source array
* @param string $prefix Key's prefix
* @param string $connector Levels connector
*/
function flatArray(array &$result, array $array, $prefix = null, $connector = '.') {
foreach ($array as $key => $value) {
if (is_array($value))
flatArray($result, $value, $prefix.$key.$connector, $connector);
else
$result[$prefix.$key] = $value;
}
}
<?php
/**
* Reindexes array with second-level value.
* @param array $array Array to reindex
* @param stirng $field Field to use as index
*/
function indexArray(array &$array, $field) {
$copy = $array;
$array = array();
foreach ($copy as $value) {
$array[$value[$field]] = $value;
}
}
<?php
/**
* Packs many arrays into one with keeping their indexes.
* @param string $indexes Array names separated by colon.
* @param array... Arrays to be packed.
* @return array Result of packing.
*/
function packArrays($indexes) {
$arrays = func_get_args();
$indexes = explode(':', array_shift($arrays));
// first algorithm
/*
$packed = array();
foreach ($arrays as $array_n => $array) {
foreach ($array as $key => $value) {
$packed[$key][$indexes[$array_n]] = $value;
}
}
krsort($packed);
*/
// second algorithm
#/*
$keys = array();
foreach ($arrays as $array) $keys = array_merge($keys, array_keys($array));
$keys = array_unique($keys);
if (empty($keys)) return array();
rsort($keys);
$packed = array_combine($keys, array_fill(0, count($keys), array()));
foreach ($arrays as $array_n => $array) {
foreach ($array as $key => $value) {
$packed[$key][$indexes[$array_n]] = $value;
}
}
#*/
return $packed;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment