Skip to content

Arr类建议增加汇总多维数组中某个键子集相同的子数组的方法 #22

@Fazime

Description

@Fazime
/**
	 * 汇总某个子集相同的到同一维
	 * @param array $array 输入的数组
	 * @param string $column 判断相同值的字段名
	 * @return array
	 */
	public static function gather($array, $column)
	{
		$data = [];
		
		if ($array) {
			foreach ($array as $item) {
				if (!is_array($item) || !self::exists($item, $column)) return [];
				$data[$item[$column]][] = $item;
			}
		}
		
		return $data;
	}


$data = [
			['id' => 2, 'aid' => 3, 'cid' => 9],
			['id' => 2, 'aid' => 5, 'cid' => 11],
		];

var_dump(Arr::gather($data, 'id'));

结果

array:1 [
  2 => array:2 [
    0 => array:3 [
      "id" => 2
      "aid" => 3
      "cid" => 9
    ]
    1 => array:3 [
      "id" => 2
      "aid" => 5
      "cid" => 11
    ]
  ]
]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions