<?php
error_reporting(-1);
$array = array(array('id' => 1, 'fid' => 2), array('id' => 2, 'fid' => 2));
class Map
{
public static function byProperty(array $array, $property)
{
$map = array();
foreach ($array as $record) {
$propValue = self::_getPropertyValue($record, $property);
$map[$propValue][] = $record;
}
return $map;
}
public static function byMultiProperty(array $array, array $properties)
{
$map = array();
$lastProperty = end($properties);
foreach($array as $record) {
$pointer = $map;
foreach($properties as $property) {
$propValue = self::_getPropertyValue($record, $property);
if(!isset($pointer[$propValue])) {
$pointer[$propValue] = array();
}
$pointer = &$pointer[$propValue];
if($property === $lastProperty) {
$pointer[] = $record;
}
}
}
return $map;
}
/**
* @param mixed $record
* @param string $property
* @return mixed
*/
private static function _getPropertyValue($record, $property)
{
if (is_array($record)) {
return isset($record[$property]) ? $record[$property] : null;
}
if (is_object($record)) {
return isset($record->$property) ? $record->$property : null;
}
throw new InvalidArgumentException(sprintf('Unsupport record type: %s',
gettype($record)));
}
}
var_dump(Map::byMultiProperty($array, array('fid', 'id')));
preferences:
50.3 ms | 402 KiB | 5 Q