Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Fazime opened this issue Jul 18, 2020 · 0 comments

Comments

@Fazime
Copy link

Fazime commented Jul 18, 2020

/**
	 * 汇总某个子集相同的到同一维
	 * @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
    ]
  ]
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant