function index($array, $key, $groups = [])
{
$result = [];
$groups = (array)$groups;
foreach ($array as $element) {
$lastArray = &$result;
foreach ($groups as $group) {
$value = getValue($element, $group);
if (!array_key_exists($value, $lastArray)) {
$lastArray[$value] = [];
}
$lastArray = &$lastArray[$value];
}
if ($key === null) {
if (!empty($groups)) {
$lastArray[] = $element;
}
} else {
$value = getValue($element, $key);
if ($value !== null) {
if (is_float($value)) {
$value = (string) $value;
}
$lastArray[$value] = $element;
}
}
unset($lastArray);
}
return $result;
}
function getValue($array, $key, $default = null)
{
if ($key instanceof \Closure) {
return $key($array, $default);
}
if (is_array($key)) {
$lastKey = array_pop($key);
foreach ($key as $keyPart) {
$array = getValue($array, $keyPart);
}
$key = $lastKey;
}
if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array)) ) {
return $array[$key];
}
if (($pos = strrpos($key, '.')) !== false) {
$array = getValue($array, substr($key, 0, $pos), $default);
$key = substr($key, $pos + 1);
}
if (is_object($array)) {
// this is expected to fail if the property does not exist, or __get() is not implemented
// it is not reliably possible to check whether a property is accessable beforehand
return $array->$key;
} elseif (is_array($array)) {
return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
} else {
return $default;
}
}
$a = [
['id'=>'1111','pform_uid'=>'2222','pform_field_id'=>'3333','value'=>'北京','customer_pform_uid'=>'4444'],
['id'=>'aaaa','pform_uid'=>'bbbb','pform_field_id'=>'cccc','value'=>'上海','customer_pform_uid'=>'dddd'],
['id'=>'1111','pform_uid'=>'BBBB','pform_field_id'=>'CCCC','value'=>'深圳','customer_pform_uid'=>'DDDD'],
];
$b = index($a, 'id', null);
//$c = index($a, null, 'id');
var_dump($b);die;
// array (size=1)
// 4444 =>
// array (size=1)
// 3333 => string '北京' (length=6)