hxss/multidimensional-array

Multidimensional array

1.0.2 2019-10-28 11:19 UTC

This package is not auto-updated.

Last update: 2024-04-23 09:02:29 UTC


README

The library allows dynamically create and use new dimensions for array. Array dimension - associative copy of the array where keys generates by user-func or automaticaly using column of arrays items.

Basic example

$mArray = new MultidimensionalArray([
	0 => [
		'name' => 'name1',
		'prop' => 'prop1',
		'key' => 'value1'
	],
	1 => [
		'name' => 'name5',
		'prop' => 'prop5',
		'key' => 'value5'
	],
	2 => [
		'name' => 'name2',
		'prop' => 'prop2',
		'key' => 'value2'
	],
	3 => [
		'name' => 'name6',
		'prop' => 'prop5',
		'key' => 'value6'
	],
]);

print_r($mArray->by('prop')); // or $mArray->byProp()

Output:

[
	'prop1' => [
		'name' => 'name1',
		'prop' => 'prop1',
		'key' => 'value1'
	],
	'prop5' => [
		'name' => 'name6',
		'prop' => 'prop5',
		'key' => 'value6'
	],
	'prop2' => [
		'name' => 'name2',
		'prop' => 'prop2',
		'key' => 'value2'
	],
];

In this example for $mArray was dynamically created dimension named prop that automatically creates associative copy of the array using items column prop for keys.

The dimension will reflect each master-arrays updates. If any item in $mArray will added/removed or master-array will be updated - dimensions array will do it too.

Changes of dimension array doesn't affect master-array.

User-func

To customise generation of dimension keys the Dimension class is used:

$mArray->addDimension(
	new Dimension('cstmProp', function($k, $v) {
		return $k . '_' . $v['prop'];
	})
);


print_r($mArray->byCstmProp());

Output:

[
	'0_prop1' => [
		'name' => 'name1',
		'prop' => 'prop1',
		'key' => 'value1'
	],
	'1_prop5' => [
		'name' => 'name5',
		'prop' => 'prop5',
		'key' => 'value5'
	],
	'2_prop2' => [
		'name' => 'name2',
		'prop' => 'prop2',
		'key' => 'value2'
	],
	'3_prop5' => [
		'name' => 'name6',
		'prop' => 'prop5',
		'key' => 'value6'
	],
];

Dimension constructor takes:

  • name;
  • (optional) callable key-generator, that should takes key and value of each master-array item and return new key for the dimension;
  • (optional, default - false) updateOnSort flag, that allows to update dimension array on master-array sorting.