Skip to content

Commit c299ea3

Browse files
committed
✨ add merge, unique, flatten and push methods
Signed-off-by: otengkwame <[email protected]>
1 parent 8af6599 commit c299ea3

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed

engine/Core/core/Helpers/Arrayz.php

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,99 @@ public function censor()
936936
return $this;
937937
}
938938

939+
/**
940+
* Merge array
941+
*
942+
* @param array ...$array
943+
* @return Base\Helpers\Arrayz
944+
*/
945+
public function merge(...$array)
946+
{
947+
948+
$this->source = arrayfy($this->source);
949+
950+
$source = $this->source;
951+
952+
if (is_array($array) && $this->isMultiArray($array)) {
953+
$source = array_merge($array, $source);
954+
}
955+
956+
$this->source = $source;
957+
958+
return $this;
959+
}
960+
961+
/**
962+
* Add more arrays by key-value
963+
* Or by two multidimensional array
964+
*
965+
* @param string|array $key
966+
* @param string $value
967+
* @return Base\Helpers\Arrayz
968+
*/
969+
public function push($key, $value = '', $asArray = false)
970+
{
971+
972+
$this->source = arrayfy($this->source);
973+
974+
$array = $this->source;
975+
976+
if (is_array($key) && $this->isMultiArray($key)) {
977+
$array = array_merge($key, $array);
978+
}
979+
980+
if (is_string($key)) {
981+
$array[$key] = $value;
982+
}
983+
984+
$this->source = $array;
985+
986+
if (!$asArray) {
987+
return $this->get();
988+
}
989+
990+
return $this->toArray();
991+
}
992+
993+
/**
994+
* Make array unique
995+
*
996+
* @return Base\Helpers\Arrayz
997+
*/
998+
public function unique()
999+
{
1000+
if ($this->isMultiArray($this->source)) {
1001+
$this->source = array_unique($this->source, SORT_REGULAR);
1002+
}
1003+
1004+
return $this;
1005+
}
1006+
1007+
/**
1008+
* Flatten a multi-dimensional array
1009+
* into a single level
1010+
*
1011+
* @param array $array
1012+
* @return array
1013+
*/
1014+
public function flatten($toArray = false)
1015+
{
1016+
$result = [];
1017+
1018+
array_walk_recursive($this->source, function($array) use (&$result)
1019+
{
1020+
$result[] = $array;
1021+
});
1022+
1023+
$this->source = $result;
1024+
1025+
if ($toArray) {
1026+
$this->source = arrayfy($result);
1027+
}
1028+
1029+
return $this;
1030+
}
1031+
9391032
/**
9401033
* Determine if the given array is associative or non-associative
9411034
*

0 commit comments

Comments
 (0)