lithium\util\Set::combine()
Creates an associative array using a $path1
as the path to build its keys, and optionally
$path2
as path to get the values. If $path2
is not specified, all values will be
initialized to null
(useful for Set::merge()
). You can optionally group the values by
what is obtained when following the path specified in $groupPath
.
Parameters
-
array
$data
Array from where to extract keys and values.
-
mixed
$path1
As an array, or as a dot-delimited string.
-
mixed
$path2
As an array, or as a dot-delimited string.
-
string
$groupPath
As an array, or as a dot-delimited string.
Returns
arrayCombined array.
Source
public static function combine($data, $path1 = null, $path2 = null, $groupPath = null) {
if (!$data) {
return [];
}
if (is_object($data)) {
$data = get_object_vars($data);
}
if (is_array($path1)) {
$format = array_shift($path1);
$keys = static::format($data, $format, $path1);
} else {
$keys = static::extract($data, $path1);
}
$vals = [];
if (!empty($path2) && is_array($path2)) {
$format = array_shift($path2);
$vals = static::format($data, $format, $path2);
} elseif (!empty($path2)) {
$vals = static::extract($data, $path2);
}
$valCount = count($vals);
$count = count($keys);
for ($i = $valCount; $i < $count; $i++) {
$vals[$i] = null;
}
if ($groupPath) {
$group = static::extract($data, $groupPath);
if (!empty($group)) {
$c = count($keys);
for ($i = 0; $i < $c; $i++) {
if (!isset($group[$i])) {
$group[$i] = 0;
}
if (!isset($out[$group[$i]])) {
$out[$group[$i]] = [];
}
$out[$group[$i]][$keys[$i]] = $vals[$i];
}
return $out;
}
}
return array_combine($keys, $vals);
}